diff --git a/lib/async_hooks.js b/lib/async_hooks.js index af5a37b749d94b..58249368dd4842 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -255,15 +255,7 @@ class AsyncResource { } const storageList = []; -const storageHook = createHook({ - init(asyncId, type, triggerAsyncId, resource) { - const currentResource = executionAsyncResource(); - // Value of currentResource is always a non null object - for (let i = 0; i < storageList.length; ++i) { - storageList[i]._propagate(resource, currentResource); - } - } -}); +let storageHook; class AsyncLocalStorage { constructor() { @@ -287,7 +279,15 @@ class AsyncLocalStorage { if (!this.enabled) { this.enabled = true; ArrayPrototypePush(storageList, this); - storageHook.enable(); + (storageHook ??= createHook({ + init(asyncId, type, triggerAsyncId, resource) { + const currentResource = executionAsyncResource(); + // Value of currentResource is always a non null object + for (let i = 0; i < storageList.length; ++i) { + storageList[i]._propagate(resource, currentResource); + } + } + })).enable(); } }