Skip to content

Commit 2f8776e

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

File tree

2 files changed

+14
-8
lines changed

2 files changed

+14
-8
lines changed

lib/internal/process/task_queues.js

Lines changed: 13 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,18 @@ 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+
const asyncResource = new AsyncResource(
165+
'Microtask',
166+
defaultMicrotaskResourceOpts,
167+
);
168+
asyncResource.callback = callback;
169+
enqueueMicrotask(FunctionPrototypeBind(runMicrotask, asyncResource));
170+
} else {
171+
// Fast path: no AsyncLocalStorage in use
172+
enqueueMicrotask(callback);
173+
}
168174
}
169175

170176
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)