nextTick Drains Before Promise Microtasks
Order callbacks across nextTick, promise microtasks, and timers so a ready signal fires before anything asynchronous can interleave.
Code
const order = [];
const readyListeners = [];
function onReady(listener) {
readyListeners.push(listener);
}
// Run the probe inside a callback tick — a timer callback is where
// production code actually runs. Module top-level evaluation has its
// own checkpoint semantics and is not where this ordering is relied on.
setTimeout(() => {
// nextTick callbacks drain before promise microtasks at the same
// checkpoint, and both finish before any timer fires
process.nextTick(() => order.push('nextTick'));
Promise.resolve().then(() => order.push('promise'));
// nextTick also beats work queued after it — handy for emitting a
// ready signal right after construction, before I/O starts
onReady(() => order.push('ready signal'));
process.nextTick(() => readyListeners.forEach((listener) => listener()));
// A timer queued now still lands after every callback above
setTimeout(() => order.push('timer'), 0);
setTimeout(() => console.log(order.join(' -> ')), 10);
}, 0);Output
Captured from a sandboxed run of this snippet in the build pipeline.
nextTick -> ready signal -> promise -> timerThe checkpoint order, measured
Inside the setTimeout probe the code queues, in source order: a process.nextTick pushing 'nextTick', a Promise.resolve().then pushing 'promise', an onReady registration, a second process.nextTick that drains readyListeners, and two timers. nextTick callbacks drain before promise microtasks at the same checkpoint, and both finish before any timer fires — so the listener registered through onReady fires ahead of the promise continuation.
The single printed line
nextTick -> ready signal -> promise -> timer
That is order.join(' -> ') after the timer chain settles: 'timer' was pushed by the setTimeout(…, 0) queued inside the same probe, and the printing timer at 10 ms can only run once every queued callback above it has finished. For production code the point is the comment’s own framing: emitting a ready signal with process.nextTick right after construction happens before I/O starts, however late the listener was registered.
The line that fires the listeners
process.nextTick(() => readyListeners.forEach((listener) => listener()));
Because this nextTick was queued after onReady’s registration but drains in the same checkpoint, even the just-registered listener runs before the promise continuation and every timer queued below it.
Interactive Tools for This Topic
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. The file defines `onReady` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.