javascript - 这段代码中的 Promise 是如何工作的?

标签 javascript promise

我对以下代码有几个问题:

  • 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 之外的其他内容,将会(几乎总是)抛出一个错误。

但是,在这种情况下,如果您没有理由怀疑代码已损坏,我非常怀疑 getGroupInfogetUserInfo构造并返回 Promise 本身。 getRemoteProfile不必为他们创建一个。

通常,您使用 Promise.resolve在需要 Promise 的情况下,但当前情况不需要实际的异步操作(例如网络请求)。

关于javascript - 这段代码中的 Promise 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50481316/

相关文章:

javascript - Promise.then() 在 Promise 解决之前执行

javascript - 使用 chai 和 Promise 捕获错误

JavaScript:为什么要获取最后插入的值?

php - Javascript 客户端如何连接到 PHP 套接字服务器?

javascript - 如何在 CHEditor 中设置浏览服务器的自定义路径

javascript - Jquery 将最后的输出作为值

javascript - 在javascript中访问文本/模板内容

javascript - 这个 Promise 链保证按这个顺序执行吗?

javascript - 返回对象内的 fetch .json。

node.js - bookshelf.js 不适用于 Passport