File tree

1 file changed

+22
-16
lines changed

1 file changed

+22
-16
lines changed
Original file line numberDiff line numberDiff line change
@@ -2743,34 +2743,40 @@ function definitelyAsync(arg, cb) {
27432743
27442744
### When to use `queueMicrotask()` vs. `process.nextTick()`
27452745
2746-
The [`queueMicrotask()`][] API is an alternative to `process.nextTick()` that
2747-
also defers execution of a function using the same microtask queue used to
2748-
execute the then, catch, and finally handlers of resolved promises. Within
2749-
Node.js, every time the "next tick queue" is drained, the microtask queue
2746+
The [`queueMicrotask()`][] API is an alternative to `process.nextTick()` that instead of using the
2747+
"next tick queue" defers execution of a function using the same microtask queue used to execute the
2748+
then, catch, and finally handlers of resolved promises.
2749+
2750+
Within Node.js, every time the "next tick queue" is drained, the microtask queue
27502751
is drained immediately after.
27512752
2753+
So in CJS modules `process.nextTick()` callbacks are always run before `queueMicrotask()` ones.
2754+
However since ESM modules are processed already as part of the microtask queue, there
2755+
`queueMicrotask()` callbacks are always exectued before `process.nextTick()` ones since Node.js
2756+
is already in the process of draining the microtask queue.
2757+
27522758
```mjs
27532759
import { nextTick } from 'node:process';
27542760

2755-
Promise.resolve().then(() => console.log(2));
2756-
queueMicrotask(() => console.log(3));
2757-
nextTick(() => console.log(1));
2761+
Promise.resolve().then(() => console.log('resolve'));
2762+
queueMicrotask(() => console.log('microtask'));
2763+
nextTick(() => console.log('nextTick'));
27582764
// Output:
2759-
// 1
2760-
// 2
2761-
// 3
2765+
// resolve
2766+
// microtask
2767+
// nextTick
27622768
```
27632769
27642770
```cjs
27652771
const { nextTick } = require('node:process');
27662772

2767-
Promise.resolve().then(() => console.log(2));
2768-
queueMicrotask(() => console.log(3));
2769-
nextTick(() => console.log(1));
2773+
Promise.resolve().then(() => console.log('resolve'));
2774+
queueMicrotask(() => console.log('microtask'));
2775+
nextTick(() => console.log('nextTick'));
27702776
// Output:
2771-
// 1
2772-
// 2
2773-
// 3
2777+
// nextTick
2778+
// resolve
2779+
// microtask
27742780
```
27752781
27762782
For _most_ userland use cases, the `queueMicrotask()` API provides a portable

0 commit comments

Comments
 (0)