tezvyn:

Microtask versus macrotask execution order in Node

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

precise grasp of event loop ordering.

OUTLINE

nextTick drains before promises, both microtask queues flush fully between each macrotask, timers and setImmediate are macrotasks.

WHAT THIS TESTS This examines deep understanding of the event loop's scheduling, distinguishing engineers who can reason about subtle async bugs from those who only use async syntactically.

A GOOD ANSWER COVERS Macrotasks are the loop's phases: timers (setTimeout, setInterval), pending I/O callbacks, the check phase (setImmediate), and close callbacks. Between every single macrotask callback, Node fully drains its microtasks. There are two microtask sources with a priority order: process.nextTick callbacks run first and entirely, then the Promise resolution queue runs and entirely. Crucially, microtasks added while draining are also processed before any macrotask resumes, which is how nextTick can starve the loop.

COMMON WRONG ANSWERS Treating nextTick and Promise.then as the same queue. Believing setTimeout(fn, 0) always fires before setImmediate; ordering between them is nondeterministic from the main module but setImmediate wins inside an I/O callback. Forgetting that microtasks fully drain between macrotasks.

LIKELY FOLLOW-UPS How can nextTick starve I/O? Why does ordering of timer versus setImmediate differ inside an I/O callback? Where does queueMicrotask fit?

ONE CONCRETE EXAMPLE Consider this code. console.log('start'); setTimeout(() => console.log('timeout'), 0); setImmediate(() => console.log('immediate')); Promise.resolve().then(() => console.log('promise')); process.nextTick(() => console.log('nextTick')); console.log('end'). The synchronous logs print first: start then end. Then microtasks drain: nextTick prints before promise because the nextTick queue has higher priority. Finally macrotasks run, so timeout and immediate print last, in an order that can vary. The reliable portion of the output is start, end, nextTick, promise, followed by timeout and immediate.

Read the original → nodejs.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.