p1 = new Promise((res,rej)=>{
console.log("p1 setTimeout");
setTimeout(()=>{
res(17);
}, 10000);
});
p2 = new Promise((res,rej)=>{
console.log("p2 setTimeout");
setTimeout(()=>{
res(36);
}, 2000);
});
function checkIt() {
console.log("Started");
let val1 = this.p1;
console.log("P1");
val1.then((data)=>{console.log("P1 => "+data)});
let val2 = this.p2;
console.log("P2");
val2.then((data)=>{console.log("P2 => "+data)});
console.log("End");
}
checkIt();
My understanding of above written JavaScript code was:
1: In callback queue, p2’s setTimeout will be first and then p1’s setTimeout (and they will execute in FIFO manner)
2: Callback queue won’t execute before microtask queue
3: In microtask queue, p1’s callback function will first and then p2’s callback function (and they will execute in FIFO manner)
4: Hence this should be deadlock.
But instead getting output:
1: p1 setTimeout
2: p2 setTimeout
3: Started
4: P1
5: P2
6: End
7: (After 2 seconds) P2 => 36
8: (After 10 seconds) P1 => 17
Doubt: How 7th and 8th line of output are coming?
I have ran the code and getting output as defined above
2
Answers
@Robin Zigmond (Please once verify this)
I think flow would be like this:
1: p1 setTimeout() will start and after 10 seconds its callback will go to callback queue
2: p2 setTimeout() will start and after 2 seconds its callback will go to callback queue
3: Earlier I though that when execution reaches val1.then((data)=>{console.log("P1 => "+data)}) it moves .then() to microtask queue (I think, this is wrong, because instead .then() of this line, will go to microtask queue when p1 is resolved)
4: Earlier I though that when execution reaches val2.then((data)=>{console.log("P2 => "+data)}) it moves .then() to microtask queue (I think, this is wrong, because instead .then() of this line, will go to microtask queue when p2 is resolved)
5: After 2 seconds, setTimeout() callback will go to callback queue and since there isn't any thing in microtask queue, hence event loop will execute it by moving it to call stack.
6: Since p2 got resolved in line 5, hence its callback function [val2.then((data)=>{console.log("P2 => "+data)})] moves to microtask queue and get executed i.e. P2 => 36 gets printed.
7: After 10 seconds, setTimeout() callback will go to callback queue and since there isn't any thing in microtask queue, hence event loop will execute it by moving it to call stack.
8: Since p1 got resolved in line 7, hence its callback function [val1.then((data)=>{console.log("P1 => "+data)})] moves to microtask queue and get executed i.e. P1 => 17 gets printed.
setTimeout
creates a new macrotask queued into the event loop after the timeout, so your promises are queued in different macrotasks and have no relation at all.