Is there a spec on the order of execution of branches of a JavaScript Promise?
Consider this code:
// Create a promise that will be resolved when we call the function `r` let r; const promise = new Promise((resolve, reject) => { r = resolve; // Store the resolver in `r`, so we can call it later. }); // When `promise` resolves, print "I am the first branch". promise.then(() => console.log("I am the first branch")); // When `promise` resolves, also print "I am the second branch". promise.then(() => console.log("I am the second branch")); // Resolve `promise` r(); The Promise promise is branched out into two branches.
From my testing, the first branch is executed before the second.
I am the first branch I am the second branch My question: Is this guaranteed by the JavaScript spec, or am I relying on an undefined behavior?
Note: I could, of course, chain the promises instead. Like this:
promise.then(() => console.log("I am the first branch")).then(() => console.log("I am the second branch")); But I would prefer to branch them if possible.
Promise.prototype.then-> 5. Return PerformPromiseThen -> 27.2.5.4.1PerformPromiseThen-> 9.a: "Ifpromise.[[PromiseState]]is pending, then AppendfulfillReactionas the last element of the List that is promise[[PromiseFulfillReactions]]"