DEV Community

Neel-Vekariya
Neel-Vekariya

Posted on

Scheduling Mechanisms In Node.js Execution.

Many developers think Node.js runs async code in the order it appears in the file. It doesn’t.

Execution order depends on synchronous code, process.nextTick(), microtask queue, and event loop phases.

When code runs, different types of work go into different queues. Like nextTick(), promise microtasks, and phase-based queues in the event loop.

First, Node.js runs all synchronous code. Things like console.log() or normal function calls. Only after that it starts dealing with queued work.

process.nextTick() runs first. It has higher priority because Node.js uses it for internal and critical callbacks that need to run right after sync code, before promises.

After that, microtasks (mainly Promises) are executed.

Once both are cleared, the event loop moves into its phases like timers, I/O callbacks, and check phase.

Between these phases, Node.js again checks nextTick() and microtasks. If anything is pending there, it runs them before continuing.

That’s basically how Node.js decides what runs first and what runs later.

Top comments (0)