diff --git a/lib/internal/process/task_queues.js b/lib/internal/process/task_queues.js index bec1fd8bd468ba..518aea930789e0 100644 --- a/lib/internal/process/task_queues.js +++ b/lib/internal/process/task_queues.js @@ -25,6 +25,7 @@ const { const { getDefaultTriggerAsyncId, + getHookArrays, newAsyncId, initHooksExist, emitInit, @@ -158,13 +159,18 @@ const defaultMicrotaskResourceOpts = { requireManualDestroy: true }; function queueMicrotask(callback) { validateFunction(callback, 'callback'); - const asyncResource = new AsyncResource( - 'Microtask', - defaultMicrotaskResourceOpts, - ); - asyncResource.callback = callback; - - enqueueMicrotask(FunctionPrototypeBind(runMicrotask, asyncResource)); + const contextFrame = AsyncContextFrame.current(); + if (contextFrame || getHookArrays()[0].length > 0) { + const asyncResource = new AsyncResource( + 'Microtask', + defaultMicrotaskResourceOpts, + ); + asyncResource.callback = callback; + enqueueMicrotask(FunctionPrototypeBind(runMicrotask, asyncResource)); + } else { + // Fast path: no AsyncLocalStorage in use + enqueueMicrotask(callback); + } } module.exports = { diff --git a/test/fixtures/errors/async_error_nexttick_main.snapshot b/test/fixtures/errors/async_error_nexttick_main.snapshot index 5c2e6e1558076c..0034454e590ab5 100644 --- a/test/fixtures/errors/async_error_nexttick_main.snapshot +++ b/test/fixtures/errors/async_error_nexttick_main.snapshot @@ -1,7 +1,7 @@ Error: test at one (*fixtures*async-error.js:4:9) at two (*fixtures*async-error.js:17:9) - at process.processTicksAndRejections (node:internal*process*task_queues:103:5) + at process.processTicksAndRejections (node:internal*process*task_queues:104:5) at async three (*fixtures*async-error.js:20:3) at async four (*fixtures*async-error.js:24:3) at async main (*async_error_nexttick_main.js:7:5)