理解 Promise.all

understanding Promise.all

考虑以下我从

中获取的代码
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/

这个想法是 运行 多个承诺和 return 一些基于其结果的复合值。

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

Promise.all 中有什么魔法可以让这一切发生吗?这种行为的规则是什么?

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

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

根据这个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.

很适合使用bluebird模块 http://bluebirdjs.com/docs/api/promise.props.html

const Promise = require("bluebird");
Promise.props({
    pictures: getPictures(),
    comments: getComments(),
    tweets: getTweets()
})
.then(function(result) {
    console.log(result.tweets, result.pictures, result.comments);
});