Node.js Developer interview question · Most asked
What is the difference between `process.nextTick`, Promise microtasks, `setImmediate` and `setTimeout(fn, 0)`?
Summary
process.nextTick callbacks run immediately after the current operation, before Promise microtasks; Promise callbacks (then, await continuations) run next; setImmediate runs in the check phase of the loop; setTimeout(fn, 0) runs in the timers phase (at least about 1 ms later).
Longer Answer
Recursive nextTick (or endless microtasks) can starve I/O because the queues are drained completely before the loop continues. Prefer queueMicrotask or setImmediate for deferring work. The order between setTimeout(0) and setImmediate in the main module is non-deterministic.
Key Points
- nextTick > microtasks > macrotasks
setImmediate: check phasesetTimeout(0): timers phase- Recursive nextTick can starve I/O
More most-asked Node.js Developer questions
- What are streams in Node.js and what is backpressure?
- What are the differences between CommonJS and ES modules in Node.js?
- Explain the phases of the Node.js event loop.
- What is Node.js and why is it well suited to I/O-heavy servers?
- How has asynchronous code evolved in Node.js: callbacks, Promises and async/await?
- Walk through how an Express app handles a request, including errors from async handlers.
- Why is CPU-bound work a problem in Node.js and how do you handle it?
- How does middleware work in Express?