Node.js Reference ยท Globals and Console
Node.js queueMicrotask() function
Reference for queueMicrotask() in Node.js: when microtasks run, how they compare to promises, timers and setImmediate, and the risk of starving the event loop.
queueMicrotask(callback) adds a function to the microtask queue. Microtasks run as soon as the current JavaScript call stack is empty, before the event loop moves on to timers, I/O or setImmediate() callbacks. Promise reactions (.then() callbacks and the code after await) use the same queue.
Use it when you want to run something "right after the current code, but not synchronously". A typical case is a function that sometimes finishes immediately and sometimes asynchronously: calling the callback from a microtask keeps its timing consistently asynchronous.
queueMicrotask(() => { console.log('runs after the current script step'); });
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
queueMicrotask(callback)
| Name | Description |
|---|---|
callback |
The function to run. It is called with no arguments. |
Returns: undefined. There is no handle, so a queued microtask cannot be cancelled.
Errors: a TypeError with code ERR_INVALID_ARG_TYPE is thrown immediately if callback is not a function. An exception thrown inside the callback is reported as an uncaught exception and can end the process.
Usage notes
- Order: microtasks run in first-in, first-out order, mixed with promise reactions. A microtask that queues another microtask adds it to the end of the same drain.
- Compared with
process.nextTick(): in CommonJS,nextTickcallbacks run before promise and microtask callbacks once the current operation finishes. In an ES module's top-level code, promise jobs run first. PreferqueueMicrotask()unless you specifically neednextTicksemantics (seeprocess.nextTick()). - Compared with
setImmediate()andsetTimeout(fn, 0): those run in later event-loop phases and let I/O happen in between. A microtask never does. - Starvation: a microtask that keeps queueing new microtasks forever prevents timers and I/O from running. Break long work into
setImmediate()chunks instead. - Errors do not become rejections. Throwing inside the callback is not turned into a rejected promise. Wrap the body in
try/catchor use a promise. - Context:
AsyncLocalStoragecontext flows into the callback, as it does for promise callbacks. - Available as a global since Node.js 11.