Skip to content

Commit

Permalink
doc: recommend queueMicrotask over process.nextTick
Browse files Browse the repository at this point in the history
We likely cannot ever deprecate process.nextTick, but we can start
steering people towards queueMicrotask for most cases.

Signed-off-by: James M Snell <jasnell@gmail.com>
Fixes: #36870
  • Loading branch information
jasnell committed Feb 22, 2021
1 parent 66ba0f1 commit e4c86c3
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions doc/api/process.md
Expand Up @@ -1730,6 +1730,41 @@ function definitelyAsync(arg, cb) {
}
```

### When to use `queueMicrotask()` vs. `process.nextTick()`

The [`queueMicrotask()`][] API is an alternative to `process.nextTick()` that
also defers execution of a function using the same microtask queue used to
execute the then, catch, and finally handlers of resolved promises. Within
Node.js, every time the "next tick queue" is drained, the microtask queue
is drained immediately after. The timing of queued microtasks is nearly
identical to `process.nextTick()` with the notable exception that the next
tick queue always executes first. There are also minor differences in the way
errors raised from within the next tick queue and microtask queue are handled.

For *most* userland use cases, the `queueMicrotask()` API provides a portable
and reliable mechanism for deferring execution that works across multiple
JavaScript platform environments and should be favored over `process.nextTick()`.
In most scenarios, `queueMicrotask()` can be a drop-in replacement for
`process.nextTick()`.

When in doubt, use `queueMicrotask()`.

```js
console.log('start');
queueMicrotask(() => {
console.log('microtask callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// microtask callback
```

Errors thrown within a queued microtask callback should be handled within the
queued callback. If they are not, the `process.on('uncaughtException')` event
handler can be used to capture and handle the errors.

## `process.noDeprecation`
<!-- YAML
added: v0.8.0
Expand Down Expand Up @@ -2720,6 +2755,7 @@ cases:
[`process.kill()`]: #process_process_kill_pid_signal
[`process.setUncaughtExceptionCaptureCallback()`]: process.md#process_process_setuncaughtexceptioncapturecallback_fn
[`promise.catch()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
[`queueMicrotask()`]: globals.md#globals_queuemicrotask_callback
[`readable.read()`]: stream.md#stream_readable_read_size
[`require()`]: globals.md#globals_require
[`require.main`]: modules.md#modules_accessing_the_main_module
Expand Down

0 comments on commit e4c86c3

Please sign in to comment.