Skip to content

Commit 6fedd50

Browse files
committed
lib: run microtasks before ticks
This resolve multiple timing issues related to promises and nextTick. As well as resolving zaldo in promise only code, i.e. our current best practice of using process.nextTick will always apply and work. Refs: nodejs#51156 Refs: nodejs#51156 (comment) Refs: nodejs#51114 Refs: nodejs#51070 Refs: nodejs#51156 PR-URL: nodejs#51267
1 parent fc102f2 commit 6fedd50

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

doc/api/cli.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -789,6 +789,21 @@ about [this configuration][`--experimental-sea-config`] for details.
789789

790790
### `--experimental-shadow-realm`
791791

792+
### `--experimental-task-ordering`
793+
794+
Enable experimental task ordering. Always drain micro task queue
795+
before running `process.nextTick` to avoid unintuitive behavior
796+
and unexpected logical deadlocks when mixing async callback and
797+
event API's with `Promise`, `async`/`await`` and `queueMicroTask`.
798+
799+
<!-- YAML
800+
added: REPLACEME
801+
-->
802+
803+
> Stability: 1 - Experimental
804+
805+
806+
792807
<!-- YAML
793808
added:
794809
- v19.0.0

lib/internal/process/task_queues.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ const {
4141

4242
const { AsyncResource } = require('async_hooks');
4343

44+
let experimentalTaskOrdering;
4445
// *Must* match Environment::TickInfo::Fields in src/env.h.
4546
const kHasTickScheduled = 0;
4647

@@ -65,8 +66,16 @@ function runNextTicks() {
6566
}
6667

6768
function processTicksAndRejections() {
69+
if (experimentalTaskOrdering === undeifned) {
70+
const { getOptionValue } = require('internal/options');
71+
experimentalTaskOrdering = getOptionValue('--experimental-task-ordering');
72+
}
73+
6874
let tock;
6975
do {
76+
if (experimentalTaskOrdering) {
77+
runMicrotasks();
78+
}
7079
while ((tock = queue.shift()) !== null) {
7180
const asyncId = tock[async_id_symbol];
7281
emitBefore(asyncId, tock[trigger_async_id_symbol], tock);
@@ -92,7 +101,9 @@ function processTicksAndRejections() {
92101

93102
emitAfter(asyncId);
94103
}
95-
runMicrotasks();
104+
if (!experimentalTaskOrdering) {
105+
runMicrotasks();
106+
}
96107
} while (!queue.isEmpty() || processPromiseRejections());
97108
setHasTickScheduled(false);
98109
setHasRejectionToWarn(false);

0 commit comments

Comments
 (0)