The Promise
execution happens as part of the microtask queue processing phase.
When you have a setTimeout
function callback scheduled, that function is added to the event loop's macrotask queue and executed when the last running code in the main execution context stack is finished. Then on the next tick of the event loop the task/function is de-queued from the event loop macrotask queue and executed by the JavaScript engine.
But in case of Promise
, if there is Promise
task queued, that will be set in a microtask queue. Which is executed after all the code in the main execution context stack is done and before the next tick of the event loop happens. The next task from the macrotask queue is only picked up when the tasks in the microtask queue is completely exhausted.
It doesn't matter if you have the setTimeout
callback scheduled at 0
milisecond. The priority is such that before the tasks in the macrotask queue is de-queued for processing in the next tick of the event loop, the microtask queue will be processed before that.
Some examples of asynchronous tasks which are queued in the macrotask queue:
setTimeout
, setInterval
, setImmediate
, I/O tasks
Examples of asynchronous tasks in microtask queue:
process.nextTick
(node), Promise
API