Please see below code:
Promise.resolve().then(() => console.log("promise1 resolved"));
Promise.resolve().then(() => console.log("promise2 resolved"));
Promise.resolve().then(() => {
console.log("promise3 resolved");
process.nextTick(() => {
console.log("Inner Next tick");
});
});
Promise.resolve().then(() => console.log("promise4 resolved"));
setImmediate(() => console.log("set immediate1"));
setImmediate(() => console.log("set immediate2"));
process.nextTick(() => console.log("next tick1"));
process.nextTick(() => console.log("next tick2"));
setTimeout(() => console.log("set timeout"), 0);
Output of this code is:
next tick1
next tick2
promise1 resolved
promise2 resolved
promise3 resolved
promise4 resolved
Inner Next tick
set timeout
set immediate1
set immediate2
What i cannot understand is why is the callback for innerTextTick i.e console.log("Inner Next tick") executed before setTimeout. As per my understanding, first the nextTick queue will be executed, nextTick 1 and 2, then all the resolved Promises and then to the timers phase, which happens as expected. But in the thid promise, i have registered a new callBack in the nextTick queue which should be called after the event loop reaches the nextTick queue again, i.e after the timers phase. But why does the event loop go back from the promise microtask queue instead of proceeding to the next phase, i.e the timers queue.