我对以下代码有几个问题:
getRemoteProfile
仅针对一种条件返回Promise.resolve
,但getRemoteProfile
调用始终与then
链接,因此当该条件失败时会发生什么?返回 promise
和返回有什么区别 Promise.resolve
,我认为返回promise.resolve
总是落入 那么function getRemoteProfile(id) { if (!id && /^_/.test(id)) { return Promise.resolve(null); } var isGroup = app.isGroupId(id); if (isGroup) { return getGroupInfo(id); } else { return getUserInfo(id.split('@')[0], app.currentUserDomain); } } function reloadProfile(id, keep) { return getRemoteProfile(id).then(function(contactProfile) { // var isGroup = app.isGroupId(id); if (contactProfile) { contactProfile.contact_id = id; if (!keep) { delete profilePromises[id]; } contactProfile.member = true; updateProfile(contactProfile.contact_id, contactProfile).then(function() { app.imagesStorage.setContactIcon(contactProfile.contact_id); }); return setDetails(contactProfile); } }); }
最佳答案
.then
无法在没有 .then
的对象上调用特性。所以,如果getRemoteProfile
曾经返回除 Promise
之外的其他内容,将会(几乎总是)抛出一个错误。
但是,在这种情况下,如果您没有理由怀疑代码已损坏,我非常怀疑 getGroupInfo
和getUserInfo
构造并返回 Promise 本身。 getRemoteProfile
不必为他们创建一个。
通常,您使用 Promise.resolve
在需要 Promise 的情况下,但当前情况不需要实际的异步操作(例如网络请求)。
关于javascript - 这段代码中的 Promise 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50481316/