From b0bc07a0b8ae02ff3fc9746e6cc3ffc19df97ba5 Mon Sep 17 00:00:00 2001 From: Bryan English Date: Thu, 1 May 2025 14:06:19 -0400 Subject: [PATCH] async_hooks: add use() method to AsyncLocalStorage This provides a way to use the `using` syntax (when available) to manage AsyncLocalStorage contexts, as an alternative to `run()`. --- doc/api/async_context.md | 37 +++++++++++++++++++ .../async_context_frame.js | 18 +++++++++ .../async_local_storage/async_hooks.js | 31 ++++++++++++++++ test/parallel/test-async-local-storage-use.js | 25 +++++++++++++ 4 files changed, 111 insertions(+) create mode 100644 test/parallel/test-async-local-storage-use.js diff --git a/doc/api/async_context.md b/doc/api/async_context.md index c60f76c746fed1..04d94d59473023 100644 --- a/doc/api/async_context.md +++ b/doc/api/async_context.md @@ -347,6 +347,43 @@ try { } ``` +### `asyncLocalStorage.use(store)` + + + +* `store` {any} +* Returns: {Disposable} A disposable object. + +Transitions into the given context, and transitions back into the previous +context when the returned disposable object is disposed. The store is +accessible to any asynchronous operations created before disposal. + +Example: + +```js +const store1 = { id: 1 }; +const store2 = { id: 2 }; + +function inner() { + // Once `using` syntax is supported, you can use that here, and omit the + // dispose call at the end of this function. + const disposable = asyncLocalStorage.use(store); + asyncLocalStorage.getStore(); // Returns store2 + setTimeout(() => { + asyncLocalStorage.getStore(); // Returns store2 + }, 200); + disposable[Symbol.dispose](); +} + +asyncLocalStorage.run(store1, () => { + asyncLocalStorage.getStore(); // Returns store1 + inner(); + asyncLocalStorage.getStore(); // Returns store1 +}); +``` + ### `asyncLocalStorage.exit(callback[, ...args])`