Search code examples
javascriptes6-promise

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 ?


Solution

  • 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.