Reputation: 124
Code sample1:
Promise.resolve().then(()=>{console.log('1')}).then(()=>{console.log('2')});
Promise.resolve().then(()=>{console.log('3')}).then(()=>{console.log('4')});
output:
1
3
2
4
Code smaple2:
Promise.resolve().then(()=>{console.log('1')});
Promise.resolve().then(()=>{console.log('2')});
Promise.resolve().then(()=>{console.log('3')});
Promise.resolve().then(()=>{console.log('4')});
output:
1
2
3
4
I suppose the first one should has same output as the second.
Because in sample 1, then
s have been call in sequence and the callbacks should be arranged one by one. But the result seems the second line Promise.resolve
cut in line.
Have I misunderstand anything?
Upvotes: 0
Views: 86
Reputation: 136707
Each callback added through a .then
will get pushed to the microtask queue when the Promise on which .then
has been called resolves.
This queue will get executed in FIFO order, and each microtask will get removed from the queue once executed.
Both cases are doing very different things, and to better understand the differences, here is a rewrite of both cases, without any chaining and reordered by execution order, but which is identical to OP's versions in terms of execution.
const cb1 = ()=>{console.log('1')};
const cb2 = ()=>{console.log('2')};
const cb3 = ()=>{console.log('3')};
const cb4 = ()=>{console.log('4')};
// microtask queue []
const p1 = Promise.resolve(); // microtask queue [p1];
const p2 = Promise.resolve(); // microtask queue [p1, p2];
// p1() => add p3
const p3 = p1.then( cb1 ); // microtask queue [p2, p3];
// p2() => add p4
const p4 = p2.then( cb3 ); // microtask queue [p3, p4];
// p3() => cb1 + add p5
const p5 = p3.then( cb2 ); // microtask queue [p4, p5];
// p4() => cb3 + add p6
const p6 = p4.then( cb4 ); // microtask queue [p5, p6];
// p5() => cb2 // microtask queue [p6];
// p6() => cb4 // microtask queue [];
const cb1 = ()=>{console.log('1')};
const cb2 = ()=>{console.log('2')};
const cb3 = ()=>{console.log('3')};
const cb4 = ()=>{console.log('4')};
// microtask queue []
const p1 = Promise.resolve(); // microtask queue [p1]
const p2 = Promise.resolve(); // microtask queue [p1, p2]
const p3 = Promise.resolve(); // microtask queue [p1, p2, p3]
const p4 = Promise.resolve(); // microtask queue [p1, p2, p3, p4]
const p5 = p1.then( cb1 ); // microtask queue [p2, p3, p4, p5]
const p6 = p2.then( cb2 ); // microtask queue [p3, p4, p5, p6]
const p7 = p3.then( cb3 ); // microtask queue [p4, p5, p6, p7]
const p8 = p4.then( cb4 ); // microtask queue [p5, p6, p7, p8]
// p5() => cb1 // microtask queue [p6, p7, p8]
// p6() => cb2 // microtask queue [p7, p8]
// p7() => cb3 // microtask queue [p8]
// p8() => cb4 // microtask queue []
Upvotes: 2