← Back to Node.js, page 6

nodejs-0115 · Medium mid

Two queues, process.nextTick and promise microtasks, schedule work inside each other. Assume a CommonJS file first. ```js Promise.resolve().then(() => { console.log('promise 1'); process.nextTick(() => console.log('nextTick inside promise')); }).then(() => console.log('promise 2')); process.nextTick(() => { console.log('nextTick 1'); Promise.resolve().then(() => console.log('promise inside nextTick')); }); process.nextTick(() => console.log('nextTick 2')); setTimeout(() => console.log('timeout'), 0); ``` What does it print, and why?

In CommonJS the nextTick queue is emptied first, then the microtask queue is emptied completely, then the loop repeats if either queue got new work. The output is nextTick 1, nextTick 2, promise 1, promise inside nextTick, promise 2, nextTick inside promise, timeout. In an ES module the first run starts inside a promise job, so promise callbacks come before nextTick callbacks.

Full answer

Node runs two queues after each operation (after the main script, and after every callback):

  1. Drain the nextTick queue.
  2. Drain the promise microtask queue completely, including microtasks added while draining.
  3. If the nextTick queue has new items, go to step 1. Otherwise continue with the event loop.

Applying it to the CommonJS file:

  • The synchronous part registers: a promise reaction (promise 1), two nextTick callbacks and a timer.
  • Step 1: nextTick 1 prints, and queues a microtask. nextTick 2 prints.
  • Step 2: the microtask queue holds [promise 1, promise inside nextTick]. promise 1 prints and schedules a nextTick and the promise 2 reaction. The queue continues: promise inside nextTick, then promise 2. The microtask queue stays busy until empty.
  • Back to step 1: nextTick inside promise prints.
  • The timer runs: timeout.

Result: nextTick 1, nextTick 2, promise 1, promise inside nextTick, promise 2, nextTick inside promise, timeout.

In an ES module, the whole module body runs as part of a promise job, so the microtask queue is drained first. The nextTick callbacks wait until it is empty. That is why the same code prints in a different order. The snippet runs the puzzle in both modes.

Starvation: because both queues are drained fully, a callback that keeps scheduling nextTick (or promises) forever blocks timers and I/O. Prefer setImmediate to yield between large pieces of work.

javascript
const { spawnSync } = require('node:child_process');

const puzzle = `
Promise.resolve().then(() => {
  console.log('promise 1');
  process.nextTick(() => console.log('nextTick inside promise'));
}).then(() => console.log('promise 2'));

process.nextTick(() => {
  console.log('nextTick 1');
  Promise.resolve().then(() => console.log('promise inside nextTick'));
});
process.nextTick(() => console.log('nextTick 2'));

setTimeout(() => console.log('timeout'), 0);
`;

const cjs = spawnSync(process.execPath, ['-e', puzzle], { encoding: 'utf8' }).stdout.trim().split('\n');
const esm = spawnSync(process.execPath, ['--input-type=module', '-e', puzzle], { encoding: 'utf8' }).stdout.trim().split('\n');
console.log('CommonJS:', cjs.join(' > '));
console.log('ES module:', esm.join(' > '));

The same puzzle runs in two child processes, once as CommonJS and once as an ES module, so the two orders can be compared. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): CommonJS: nextTick 1 > nextTick 2 > promise 1 > promise inside nextTick > promise 2 > nextTick inside promise > timeout ES module: promise 1 > promise 2 > nextTick 1 > nextTick 2 > nextTick inside promise > promise inside nextTick > timeout

Key points

  • nextTick queue first, then the whole microtask queue, then repeat.
  • Work added during draining is processed before the loop continues.
  • ES modules start inside a promise job, so microtasks go first.
  • Endless nextTick or promise recursion starves timers and I/O.

Common mistakes

  • Thinking nextTick and promises share one queue.
  • Stopping the trace after the first microtask.
  • Assuming ES modules and CommonJS behave the same.
  • Using recursive nextTick for long loops.

Follow-ups

  • How do you split a long loop so that I/O can run in between?
  • What does queueMicrotask do compared with nextTick?
  • Why can a nextTick loop freeze a server?

Tips

  • Say the three-step rule.
  • Mention the ES module difference.
  • Name starvation as the practical risk.