skip to content

In a CommonJS Node.js script, in what order do process.nextTick, resolved-promise .then and setTimeout(0) callbacks run, and why?

level: middleimportance: must knowfreq 70%

answer

  1. two queues, two owners
  2. Node's queue drains first
  3. repeat until both are empty
  4. after every callback, not per phase

basics

~20 s

Synchronous code first, then every process.nextTick callback, then every promise callback, then the timeout. Node drains its own next tick queue before V8's microtask queue after each operation; setTimeout waits for the loop's timers phase.

solid answer

~50 s

The order is synchronous code, then `process.nextTick` callbacks, then promise `.then` callbacks, then the `setTimeout(0)` callback. After every operation it runs from the loop (the main script, each timer, each immediate, each I/O callback) Node drains its own next tick queue completely, then asks V8 to drain the microtask queue that holds promise reactions and `queueMicrotask()` callbacks, and repeats while that drain queued more ticks. Only when both are empty does the loop continue, and a timer runs only in its timers phase. Two consequences: a tick scheduled inside a `.then` waits for the whole microtask queue, chained `.then`s included, and two due timers are separated by a full drain, so a tick queued in the first runs before the second timer. In an ES module entry the top-level order flips, which is why the question says CommonJS.

code

javascript · 11 lines
javascript
// order.cjs
Promise.resolve().then(() => {
  console.log('p1');
  process.nextTick(() => console.log('tick from p1'));
}).then(() => console.log('p2'));

process.nextTick(() => {
  console.log('t1');
  Promise.resolve().then(() => console.log('promise from t1'));
});
process.nextTick(() => console.log('t2'));

go deeper

for a junior

Recall the order: synchronous code, nextTick callbacks, promise callbacks, then timers, and that nextTick is a Node API with no browser counterpart.

for a middle

Explain the drain loop: Node's tick queue empties, then V8's microtask queue, repeating until both are empty, after every callback rather than once per phase.

for a senior

Trace nested scheduling correctly and treat cross-queue order as an implementation detail: chain real dependencies instead of relying on which queue drains first.

for a principal

Decide whether a codebase should allow process.nextTick at all when queueMicrotask() gives one standard queue whose order behaves the same in both module formats.

## Two queues, one owned by Node Node keeps **two** queues of "run this as soon as the current code finishes" callbacks, and the ordering question is entirely about how it interleaves them: - The **next tick queue**, filled by `process.nextTick()`. It belongs to Node itself; it is a plain JavaScript queue inside Node's internals. - The **microtask queue**, filled by promise reactions (`.then`, `.catch`, `.finally`, the continuation after an `await`) and by `queueMicrotask()`. It belongs to V8, the JavaScript engine, and is the same queue the language specification describes for promise jobs. `setTimeout(fn, 0)` uses neither. It registers a libuv timer, which can only run when the event loop reaches its timers phase. ## The drain algorithm After **every** operation that Node runs from C++ into JavaScript (the main script, each timer callback, each `setImmediate()` callback, each I/O callback), Node runs an internal routine (in `lib/internal/process/task_queues.js`) that does this: 1. Run every callback in the next tick queue, including ones added while it is draining. 2. Ask V8 to run the whole microtask queue, including microtasks added while it is draining. 3. If step 2 queued new tick callbacks, go back to step 1. Otherwise stop and let the event loop continue. So for a CommonJS main script: ```js setTimeout(() => console.log('timeout'), 0); Promise.resolve().then(() => console.log('promise')); process.nextTick(() => console.log('nextTick')); console.log('sync'); ``` prints `sync`, `nextTick`, `promise`, `timeout`. The script itself is the first operation; when it finishes, the tick queue drains, then the microtask queue, and only then does the loop start and reach the timer. ## Nesting: what a callback schedules The loop in the algorithm has two consequences that interviewers like to probe: - A **promise scheduled inside a tick callback** waits until the *entire* tick queue is empty, including tick callbacks queued after it. - A **tick scheduled inside a promise callback** waits until the *entire* microtask queue is empty, including `.then` callbacks chained after the current one. It does not jump ahead of promise jobs that were already pending. | Scheduled from | `process.nextTick(fn)` runs | `Promise.resolve().then(fn)` runs | |---|---|---| | synchronous CommonJS code | first | after all tick callbacks | | inside a tick callback | later in the same tick drain | after the tick queue is empty | | inside a promise callback | after the microtask queue is empty | later in the same microtask drain | ## Draining after each callback, not once per phase Because the drain runs after every callback, two timers that are due at the same moment do not run back to back. In: ```js setTimeout(() => { console.log('timer 1'); process.nextTick(() => console.log('tick')); Promise.resolve().then(() => console.log('promise')); }, 0); setTimeout(() => console.log('timer 2'), 0); ``` the output is `timer 1`, `tick`, `promise`, `timer 2`. Node's timer code explicitly drains both queues between timer callbacks, and between immediates in the check phase, as it does after each I/O callback. ## Where `queueMicrotask()` fits `queueMicrotask(fn)` puts `fn` on V8's microtask queue, so it is ordered **first-in, first-out with promise reactions**, not with tick callbacks. When both are queued from the same synchronous CommonJS code, the `process.nextTick()` callback therefore runs before the `queueMicrotask()` callback even if the microtask was queued first. ## Reasoning through any ordering question When an interviewer shows a snippet that mixes these APIs, walk it in a fixed order rather than guessing: 1. Run the synchronous code to the end, noting what each line queues and where. 2. Drain the next tick queue completely, appending anything a tick callback queues. 3. Drain the microtask queue completely (promise reactions and `queueMicrotask()` in the order they were queued), again appending new ones. 4. If step 3 queued ticks, return to step 2. 5. Only now let the loop continue to timers, I/O and immediates, and repeat steps 2 to 4 after each callback it runs. ## Caveats worth naming - **ES module entry points reverse the top-level order.** Node evaluates an ES module while it is already draining the microtask queue, so promise and `queueMicrotask()` callbacks scheduled at the module's top level run before tick callbacks. Inside later timer or I/O callbacks the CommonJS order returns. - **Order is not a contract to build on.** Code that only works because a tick ran before a promise job is fragile; chain the dependency explicitly instead. - **Both queues can starve the loop.** Callbacks that keep scheduling more work in either queue prevent the loop from ever reaching timers or I/O.

  • If a .then callback calls process.nextTick(), does that tick run before the next .then in the chain?
    No. Node is in the middle of the microtask drain, which V8 runs to completion, so the chained `.then` and any other pending promise jobs run first. The tick callback runs when Node returns to its next tick queue after the microtask queue is empty.
  • Two setTimeout(0) callbacks are due together and the first queues a promise callback; where does that promise callback run?
    Between the two timer callbacks. Node drains the next tick queue and the microtask queue after each timer callback, not once at the end of the timers phase, so the promise callback runs before the second timer callback starts.
  • Where does a queueMicrotask() callback land relative to process.nextTick() and promise callbacks?
    `queueMicrotask()` uses V8's microtask queue, so it is ordered first-in, first-out with promise reactions. When both are queued from synchronous CommonJS code, it therefore runs after the pending `process.nextTick()` callbacks, even ones queued later, and in queue order alongside `.then` callbacks.

  • Promise callbacks queued by a CommonJS script run before its process.nextTick callbacks.
  • Node drains the tick and promise queues once per loop iteration.
  • A nextTick queued inside a .then runs before the next promise job.
  • queueMicrotask() puts its callback on the same queue as process.nextTick().
  • setTimeout(fn, 0) runs before promise callbacks because its delay is zero.