@@ -2743,34 +2743,40 @@ function definitelyAsync(arg, cb) {
|
2743 | 2743 |
|
2744 | 2744 | ### When to use `queueMicrotask()` vs. `process.nextTick()`
|
2745 | 2745 |
|
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 |
2750 | 2751 | is drained immediately after.
|
2751 | 2752 |
|
| 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 | +
|
2752 | 2758 | ```mjs
|
2753 | 2759 | import { nextTick } from 'node:process';
|
2754 | 2760 |
|
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')); |
2758 | 2764 | // Output:
|
2759 |
| -// 1 |
2760 |
| -// 2 |
2761 |
| -// 3 |
| 2765 | +// resolve |
| 2766 | +// microtask |
| 2767 | +// nextTick |
2762 | 2768 | ```
|
2763 | 2769 |
|
2764 | 2770 | ```cjs
|
2765 | 2771 | const { nextTick } = require('node:process');
|
2766 | 2772 |
|
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')); |
2770 | 2776 | // Output:
|
2771 |
| -// 1 |
2772 |
| -// 2 |
2773 |
| -// 3 |
| 2777 | +// nextTick |
| 2778 | +// resolve |
| 2779 | +// microtask |
2774 | 2780 | ```
|
2775 | 2781 |
|
2776 | 2782 | For _most_ userland use cases, the `queueMicrotask()` API provides a portable
|
|
0 commit comments