javascript - 理解 Promise.all

标签 javascript es6-promise

考虑以下我从 https://stackoverflow.com/a/28250704/460084 获取的代码

function getExample() {
    var a = promiseA(…);
    var b = a.then(function(resultA) {
        // some processing
        return promiseB(…);
    });
    return Promise.all([a, b]).spread(function(resultA, resultB) {
        // more processing
        return // something using both resultA and resultB
    });
}

以及我创建的代码演示 https://jsfiddle.net/Lsobypup/

这个想法是运行多个 Promise 并根据其结果返回一些复合值。

我不明白的是为什么在上面的代码中promiseA只运行一次?在我看来,使用 Promise.all([a, b]) 它应该首先在评估 a 时运行,然后在评估 b 时再次运行,因为它依赖于 a。但正如演示所示,这并没有发生。

Promise.all 中有什么魔法可以实现这一点吗?这种行为有哪些规则?

最佳答案

var b = a.then(function(resultA) {
        // some processing
        return promiseB(…);
    });

这是链接 a 的结果,这意味着如果 a 处于已完成状态,将立即调用回调。您对 Promise a 的解析首先发生,因为它是在 all() 调用中首先遇到的。 一旦实现,最终值(value)将始终遵循 promise 。

据此MDN reference :

Internally, a promise can be in one of three states:

  • Pending, when the final value is not available yet. This is the only state that may transition to one of the other two states.
  • Fulfilled, when and if the final value becomes available. A fulfillment value becomes permanently associated with the promise. This may be any value, including undefined.
  • Rejected, if an error prevented the final value from being determined. A rejection reason becomes permanently associated with the promise. This may be any value, including undefined, though it is generally an Error object, like in exception handling.

关于javascript - 理解 Promise.all,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34743095/

相关文章:

javascript - $(this :selected). val() 或 .text() 不返回任何内容

javascript - API 调用后从 Promise 返回数据并将其存储在变量中

javascript - Promise.resolve(promise) 的用例是什么?

async-await - Flow 确实在 async/await 之后继续将变量解释为 Promises

javascript - 从 Dart 创建 js 对象

JavaScript 评估速记问题

javascript - typescript 不强制类型

javascript - 无法将变量名称从一个 Node 模块发送到另一个 Node 模块,以将其用作使用 socket.io 的聊天应用程序的房间名称

node.js - Knex.js 多链式查询

typescript - 将 Promise 与 async/await 结合使用