rules/async-context.md
GitHubAsyncLocalStorage additions
Source: doc/api/async_context.md at nodejs/node ab476eccd03. Verified by
examples/als-scope.mjs and examples/als-options.mjs.
new AsyncLocalStorage({ defaultValue, name }) (v24.0.0)
getStore()returnsdefaultValuewhen no store has been entered.als.run(undefined, fn)andals.exit(fn)giveundefinedinsidefn, notdefaultValue.als.nameis the given name, or''when none was given.
als.withScope(store) → RunScope (v25.9.0, v24.20.0; Stability 1)
{
using _ = als.withScope(store); // enter
work(); // getStore() === store
} // previous store restored, also on throw
const s = als.withScope(store); /* ... */ s.dispose(); // manual; idempotent
RunScopehasdispose()and[Symbol.dispose](). The class is not exported.- Without
using, a missingdispose()leaves the store entered for the rest of the current execution context. That is the same asenterWith(). - Async trap: in an
asyncfunction, the scope entered before the firstawaitstays visible to the caller after it gets the promise back. This was verified:await f()followed bygetStore()in the caller still returns the leaked store. Useals.run(store, async () => ...)for async work. - Prefer
withScopeoverenterWithfor block-scoped sync context (request parsing, middleware that must restore on throw).
The diagnostics_channel counterpart is channel.withStoreScope(data) (v26.1.0). See
diagnostics-channel.md.