0

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.

2 Answers 2

0

https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick:

You may have noticed that process.nextTick() was not displayed in the diagram, even though it's a part of the asynchronous API. This is because process.nextTick() is not technically part of the event loop. Instead, the nextTickQueue will be processed after the current operation is completed, regardless of the current phase of the event loop. Here, an operation is defined as a transition from the underlying C/C++ handler, and handling the JavaScript that needs to be executed.

Looking back at our diagram, any time you call process.nextTick() in a given phase, all callbacks passed to process.nextTick() will be resolved before the event loop continues.

Sign up to request clarification or add additional context in comments.

Comments

0

Because in the global scope of main executed file, the Event Loop doesn't come into play yet. All the Promise.resolve() in global goes into MicrotaskQueue and all global nextTick goes into nextTick queue. So your inner nextTick goes into the nextTick queue before the Timeouts Phase of the Event Loop run for the first time. That's also why promise4 resolved even before Inner Next Tick too.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.