process.nextTick() schedules a callback to run immediately after the current operation, before the event loop continues.
It runs:
- Before Promises
- Before timers (
setTimeout) - Before moving to next event loop phase
Execution order
1. Current code
2. process.nextTick() ← runs here
3. Promise microtasks
4. Event loop phases (timers, poll, check...)
Example
console.log("start");
process.nextTick(() => console.log("nextTick"));
Promise.resolve().then(() => console.log("promise"));
setTimeout(() => console.log("timeout"), 0);
console.log("end");
Output
start
end
nextclick (next click queue)
promise (microtask queue)
timeout (macro task queue)
When it executes
- After current process /code
- Before event loop
↓
process.nextTick queue runs
↓
Promise microtask queue runs
↓
Event loop phases start
process.nextTick() schedules a callback to run immediately after the current operation, before the event loop continues and even before Promise microtasks. It uses a separate queue and has higher priority, which is why overusing it can block the event loop.Sometimes callback runs immediately, sometimes later → inconsistent
function getData(callback) {
callback("data"); // sync execution
}
With nextclick, always async, predictable behavior (consistent behavior)
Callback will run before next event loop
function getData(callback) {
process.nextTick(() => {
callback("data");
});
}
2. Error Handling
Ensures:
- Errors are always handled asynchronously
- Matches Node.js API design
function readFile(file, callback) {
if (!file) {return process.nextTick(() => {
callback(new Error("File required"));
});
}
// async logic...
}
No comments:
Post a Comment