Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise.resolve vs new Promise(resolve) in vanilla js

The relevant question told me that resolving to a new promise, which is scheduled for the next loop even though it's immediately resolved. However, the comment part seems to be counter examples.

var p1 = Promise.resolve("p1")

/* console order will be "p2" "p1" */ 
// pattern1
// var p2 = Promise.resolve(Promise.resolve("p2")); 
// pattern2
// var p2 = Promise.resolve(new Promise(function(resolve, reject){
//   resolve("p2")
// }))

/* console order will be "p1" "p2" */ 
// pattern3
var p2 = new Promise(function(resolve, reject){
    resolve(Promise.resolve("p2"));
}) 

p2.then(function(value){
  console.log(value);
})
p1.then(function(value){
  console.log(value);
})

weird in Chrome v61.0.3163.91, but normal in Node.js.

NOTE: the question is not the same with the popular one. Just focus on the order question: Why the different patterns produce different order? And explaination in terms of Event Loop would be preferred.

like image 325
PageYe Avatar asked Oct 17 '22 05:10

PageYe


1 Answers

promise.then's callback won't be appended to the microtask queue until the promise is in the status of settled(fulfilled or rejected). Microtask will be executed sequentially from queue, i.e. "First In, First Out".

In the implementation of Chrome v61.0.3163.91, once p1 created, it is always in the status of resolved. p2 in pattern1 and pattern2 are in the status of resolved, while p2 in pattern3 are in the status of pending.

Therefore, in pattern1 and pattern2, p2.then's callback is appended to the microtask queue first and executed first. In pattern3, although p2.then is executed first, it appends the callback to the microtask queue in the future, since the promise is still in the status of pending. So p1.then's callback executed first.

like image 95
PageYe Avatar answered Oct 21 '22 00:10

PageYe