kofifus
kofifus

Reputation: 19305

understanding Promise.all

Consider the following code which I took from 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
    });
}

and a demo of the code I created https://jsfiddle.net/Lsobypup/

The idea is to run multiple promises and return some composite value based on their results.

What I don't understand is why in the code above promiseA runs only once ? it seems to me that with Promise.all([a, b]) it should run first when a is evaluated and then again when b is evaluated as it depends on a. But as the demo shows this does not happen.

Is there some magic in Promise.all to make this happen ? and what are the rules around this kind of behaviour ?

Upvotes: 0

Views: 228

Answers (2)

аlex
аlex

Reputation: 5698

It will be great for use bluebird module 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);
});

Upvotes: 0

varevarao
varevarao

Reputation: 2186

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

This is chaining the result of a, which means if a is in a fulfilled state, the callback would immediately be invoked. Your resolution for promise a happens first as it's encountered first in the all() call. Once fulfilled, the final value sticks to the promise throughout.

As per this 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.

Upvotes: 1

Related Questions