Skip to content

Commit a6615a8

Browse files
committed
process: preserve AsyncLocalStorage in queueMicrotask only when needed
1 parent d0c1024 commit a6615a8

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

lib/internal/process/task_queues.js

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ const {
2525

2626
const {
2727
getDefaultTriggerAsyncId,
28+
getHookArrays,
2829
newAsyncId,
2930
initHooksExist,
3031
emitInit,
@@ -158,13 +159,19 @@ const defaultMicrotaskResourceOpts = { requireManualDestroy: true };
158159
function queueMicrotask(callback) {
159160
validateFunction(callback, 'callback');
160161

161-
const asyncResource = new AsyncResource(
162-
'Microtask',
163-
defaultMicrotaskResourceOpts,
164-
);
165-
asyncResource.callback = callback;
166-
167-
enqueueMicrotask(FunctionPrototypeBind(runMicrotask, asyncResource));
162+
const contextFrame = AsyncContextFrame.current();
163+
if (contextFrame || getHookArrays()[0].length > 0) {
164+
// Slow path: need async hooks or context frame propagation
165+
const asyncResource = new AsyncResource(
166+
'Microtask',
167+
defaultMicrotaskResourceOpts,
168+
);
169+
asyncResource.callback = callback;
170+
enqueueMicrotask(FunctionPrototypeBind(runMicrotask, asyncResource));
171+
} else {
172+
// Fast path: no hooks, no context frames - just enqueue directly
173+
enqueueMicrotask(callback);
174+
}
168175
}
169176

170177
module.exports = {
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
Error: test
22
at one (*fixtures*async-error.js:4:9)
33
at two (*fixtures*async-error.js:17:9)
4-
at process.processTicksAndRejections (node:internal*process*task_queues:103:5)
4+
at process.processTicksAndRejections (node:internal*process*task_queues:104:5)
55
at async three (*fixtures*async-error.js:20:3)
66
at async four (*fixtures*async-error.js:24:3)
77
at async main (*async_error_nexttick_main.js:7:5)

0 commit comments

Comments
 (0)