process: preserve AsyncLocalStorage in queueMicrotask only when needed

PR-URL: https://github.com/nodejs/node/pull/60913
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
This commit is contained in:
Gürgün Dayıoğlu
2025-12-21 02:12:15 +01:00
committed by GitHub
parent ed6ec9626e
commit a65421a679
2 changed files with 14 additions and 8 deletions

View File

@@ -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 = {

View File

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