Defer callback execution
An API must invoke a callback asynchronously while allowing the current function to finish initializing state first.
Node.js · Pipe
process.nextTick() defers a callback until the current JavaScript operation finishes, then runs it before the event loop continues. It can also pass extra arguments to that callback.
Calling process.nextTick() places a callback in Node.js's next-tick queue. Node drains that queue after the current JavaScript stack or operation finishes and before continuing the event loop; optional arguments are supplied to the callback when it runs.
process.nextTick(callback, ...args?): void| Name | Type | Description |
|---|---|---|
callback | Function | Function to place in the next-tick queue. |
...args | any | Optional values passed to callback when it is invoked. |
void
console.log('start');
process.nextTick((name) => {
console.log(`next tick: ${name}`);
}, 'worker');
console.log('end');The synchronous logs appear first; the callback runs after the current JavaScript operation completes.
An API must invoke a callback asynchronously while allowing the current function to finish initializing state first.
Error handling, cleanup, or retry logic must run before the event loop advances.
A deferred callback needs values supplied without creating a closure.
It schedules a callback in the next-tick queue. Node drains that queue after the current JavaScript operation completes and before the event loop continues.
Follow-up: How does it compare with setImmediate()? setImmediate() runs on a later event-loop iteration, while nextTick runs before the event loop proceeds.
The callback is called with the additional values supplied after the callback argument. Its signature is process.nextTick(callback, ...args?).
Follow-up: How can queueMicrotask receive equivalent values? Capture them in a closure or use a bound function.
Recursive scheduling can keep the next-tick queue from emptying and starve I/O. Use it sparingly and avoid unbounded chains.
Follow-up: What alternative is generally preferred when nextTick-specific capabilities are not needed? queueMicrotask().
queueMicrotask()setImmediate()setTimeout()event loop