I am sure that all the codes below, except
So I expect the result is resolve(Promise.resolve(p2))
, are synchronous.p2
first since the p2.then
run first. However p1
comes out first in console.
MDN has nothing related to the question. Does the spec has some details? Can someone make it clear step by step what happens in resolving a promise?
Chrome v60.0.3112.113
My code is:
var p1 = new Promise(function(resolve, reject){
resolve("p1");
});
var p2 = new Promise(function(resolve, reject){
//resolve("p2");
var tempP = Promise.resolve("p2"); // for better description in discussion
resolve(tempP);
});
p2.then(function(value){
console.log(value)
})
p1.then(function(value){
console.log(value);
});
I am sure that all the codes below, except
resolve(Promise.resolve(p2))
, are synchronous.
No. then
callbacks are never called synchronously, they're always asynchronous (and that's good). That means their relative order is indeterminate, and depends on when the respective promise was fulfilled. If you ever care about the order of callbacks, make it explicit by chaining the promises onto each other.
The order of fulfillment in your example depends on the value that you resolved the promises with. Notice that the new Promise
callback and therefore your resolve
are synchronous, in both p1
and p2
. Every resolution is put into a queue - at least with native ES6 promises that you appear to be using. The difference is that your p2
is resolved with Promise.resolve("p2")
, which will resolve p2
with the result of that other promise - which is put back onto the queue again. Therefore the fulfillment of p1
happens first, and the callback is called before the fulfillment callback of p2
.
So what happens step-by-step is
new Promise
calls the constructor callback, which in turnresolve
s the new promise with the value "p1"
- fulfilling itnew Promise
returns and the value is assigned to p1
.new Promise
calls the constructor callback, which in turn"p2"
resolve
s the new promise with it - which adds another resolve
as a callback for when that promise completesnew Promise
returns and the value is assigned to p2
.p2.then
is called and registers the fulfillment callbackp1.then
is called and schedules the fulfillment callback, as p1
is already fulfilledAfter that, asynchronously:
p2
with the value "p2
- fulfilling it and scheduling its registered callbacksp1
callback is called and logs "p1"
p2
callback is called and logs "p2"