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.sstatic.net/lb9Zr.png)
Promise.resolve('2').then(console.log);
console.log('3');
This code will have to come through the next steps:
so in the console we have following output: 3 2 1 (https://i.sstatic.net/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.sstatic.net/bvPEp.png)
So, I suggest next steps:
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
setTimeout(()=>{
console.log('1');
}, 0);
Promise.resolve(setTimeout(()=>{
console.log('2');
}));
console.log('3');
This example is probably not what you intended - you are calling setTimeout synchronously here and creating a promise fulfilled to its timeoutId. It's the same as:
setTimeout(()=>{
console.log('1');
}, 0);
let id = setTimeout(()=>{
console.log('2');
});
Promise.resolve(id);
console.log('3');
Without getting into spec/platform terminology too much: Promise resolution always comes before I/O and stuff like timers. Whenever platforms run handlers for I/O they will "run all microtasks" after each operation (so you can "starve the event loop" with microtasks - we even have a warning for process.nextTick in the docs in Node).