As described in ECMAScript 6 Getting Started, promise.resolve (‘foo’) is equivalent to New Promise(resolve => resolve(‘foo’)). What if the resolve argument is a Promise object? Is that still equivalent?
Demo1
let p1 = Promise.resolve(1);
let p2 = new Promise(resolve= > resolve(1));
console.log(p1);
console.log(p2);
// Promise {<fulfilled>: 1}
// Promise {<fulfilled>: 1}
Copy the code
Demo2
let p = Promise.resolve(1);
let p3 = Promise.resolve(p);
let p4 = new Promise(resolve= > resolve(p));
console.log(p3);
console.log(p4);
// Promise {<fulfilled>: 1}
// Promise {<pending>}
Copy the code
It turns out that p3 and P4 are in different states
Demo3
let p = Promise.resolve(1);
let p3 = Promise.resolve(p);
let p4 = new Promise(resolve= > resolve(p));
p4.then(() = > console.log('promise1'))
.then(() = > console.log('promise2'));
p3.then(() = > console.log('promise3'))
.then(() = > console.log('promise4'))
.then(() = > console.log('promise5'));
// promise3
// promise4
// promise1
// promise5
// promise2
Copy the code
The callback function specified in P4 was found to delay two sequential executions. Looking at the equivalent code related to Demo4, then execution is delayed for both sequences.
Demo4
Promise.resolve(thenable) equals new Promise(resolve =>{promise.resolve (). Then (()=>{p.hen (resolve); }); });
let p = Promise.resolve(1);
let p3 = Promise.resolve(p);
Resolve (thenable) is equivalent to the following code
let p4 = new Promise(resolve= > {
Promise.resolve().then(() = >{
p.then(resolve);
});
});
p4.then(() = > console.log('promise1'))
.then(() = > console.log('promise2'));
p3.then(() = > console.log('promise3'))
.then(() = > console.log('promise4'))
.then(() = > console.log('promise5'));
Copy the code
For the first macro task execution, A is added to the microtask queue when it encounters block A as selected in the figure above() => console.log('promise3')
Join the microtask queue, and the two callback functions in the microtask queue are executed before the end of the loop.
() => console.log(‘promise3’) execute to print promise3; Log () => console.log(‘promise4’) is put into a queue to continue execution.
If () => console.log(‘promise4’) is queued, () => console.log(‘promise4’) is queued, and () => console.log(‘promise4’) is queued. () => console.log(‘promise5’) will be queued. So print promise1 and promise5 at once
reference
Promise. Resolve () with new Promise(r => r(v))
Async await and Promise microtask execution order problem
What’s the difference between resolve(thenable) and resolve(‘non-thenable-object’)?