community! I've been recently discovering how JavaScript works and came across interesting moment with order of elements being executed in Job Queue and Task Queue. As we all know, Job Queue has higher priority then Task Queue. But is it correct, that if async function like Promise.resolve depends on lower priority functions in Task Queue, than before completing the async function, we need to execute all functions from Task Queue ?
This can be seen on the example I've provided below:
setTimeout(()=>{
console.log('1');
}, 0);
(https://i.stack.imgur.com/lb9Zr.png)
Promise.resolve('2').then(console.log);
console.log('3');
This code will have to come through the next steps:
- setTimeout is added to call stack
- setTimeout is pushed to WebAPI and popped from call stack
- Promise.resolve, after being recognized as async function returning promise, is pushed in Job Queue and in the same time setTimout callback is pushed in Task Queue
- console.log('3') is pushed on the call stack and executed and popped from call stack
- As call stack is empty, event loop pushes Promise.resolve on call stack and produces console.log function to be executed
- When the previous functions are popped, only then setTimeout callback will be pushed on call stack and executed
so in the console we have following output: 3 2 1 (https://i.stack.imgur.com/0eApX.png)
However, if we modify the code to be:
setTimeout(()=>{
console.log('1');
}, 0);
Promise.resolve(setTimeout(()=>{
console.log('2');
}));
console.log('3');
We will have output: 3 1 2
(https://i.stack.imgur.com/bvPEp.png)
So, I suggest next steps:
- setTimeout is added to call stack
- setTimeout is pushed to WebAPI and popped from call stack
- Promise.resolve, after being recognized as async function returning promise, is pushed in Job Queue and in the same time setTimout callback is pushed in Task Queue
- console.log('3') is pushed on the call stack and executed and popped from call stack
- As call stack is empty, event loop pushes Promise.resolve on call stack, however this function depends on setTimeout which goes to WebAPI and then pushed in Task Queue. !!! And it is the most interesting part: elements in Task Queue executed using FIFO (first-in first-out) principle, so, as I suggest, event loop is forced to push first setTimout callback on call stack, which is blocking the one on which Promise.resolve is depending
- After first setTimeout callback is executed, popped -> setTimeout callback on which Promise.resolve depends now can be pushed, executed and popped.
To sum up, is it correct, that if async function like Promise.resolve depends on lower priority functions in Task Queue, than before completing the async function, we need to execute all functions from Task Queue ? P.S. I've attached screenshots of code + result using chrome console