Skip to content

fix: honor process.nextTick ordering before microtasks - #21

Open
johnhldiver-beep wants to merge 1 commit into
made-in-common:mainfrom
johnhldiver-beep:fix/10-nexttick-ordering
Open

johnhldiver-beep wants to merge 1 commit into
made-in-common:mainfrom
johnhldiver-beep:fix/10-nexttick-ordering

Conversation

@johnhldiver-beep

Copy link
Copy Markdown

Fixes #10.

vite-node ran process.nextTick callbacks after Promise/queueMicrotask callbacks, violating Node's documented event-loop guarantee. Repro: node prints S N P Q T I, vite-node printed S P Q N I T.

Root cause: ViteNodeRunner.runModule executes the transformed module body inside an async IIFE that is awaited from within a deep promise chain, so the module's top-level synchronous code runs inside V8's microtask checkpoint — Promise/queueMicrotask callbacks it registers drain before its nextTick callbacks.

Fix (in src/client.ts only): execute the module body on a setImmediate macrotask instead of awaiting it synchronously, mirroring how native CommonJS entry modules run. The error path is safe: the module body is wrapped in an async IIFE, so fn() never throws synchronously and resolve() adopts rejections correctly; the finally cleanup still runs.

Tests: new test/src/event-loop-order.ts fixture (the exact repro) and test/test/event-loop.test.ts (1 regression test). The test asserts the deterministic part only — output starts with SNPQ, N before P and N before Q. It deliberately does not assert T-vs-I ordering (timer vs check phase is flaky under load; documented in the test comment). Full suite: 7 files / 35 tests passed, 0 failed. Build clean (tsc --noEmit, tsdown, eslint).

Note: unrelated to #8 (which has its own repro-test PR #9) and to #18 (filed separately as #20).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

vite-node seems to incorrectly orders process.nextTick relative to microtasks

1 participant