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
setTimeoutcalls are made, by which point of course the "microtask queue" is empty. Actually even that's not quite right, becausesetTimeoutdoesn't put its callback into the "callback queue" until the timeout completes, so there is never more than one item in it at any one point.setTimeout) doesn't even add anything to the "callback queue" until the timeout period has passed.