Skip to content

Commit 2846886

Browse files
committed
lib: AsyncLocalStorage.bind() and AsyncLocalStorage.snapshot()
1 parent 19bcba0 commit 2846886

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

doc/api/async_context.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,48 @@ this time will print the stack trace and exit. See
147147
Creating an async resource within the `onPropagate` callback will result in
148148
a recursive call to `onPropagate`.
149149

150+
### `asyncLocalStorage.bind(fn, thisArg)`
151+
152+
<!-- YAML
153+
added: REPLACEME
154+
-->
155+
156+
* `fn` {Function} The function to bind to the current execution context.
157+
* `thisArg` {any}
158+
159+
Binds the given function to the current execution context.
160+
161+
The returned function will have an `asyncResource` property referencing
162+
the `AsyncResource` to which the function is bound.
163+
164+
### `asyncLocalStorage.snapshot()`
165+
166+
<!-- YAML
167+
added: REPLACEME
168+
-->
169+
170+
Returns a callback that captures the current async context and invokes a callback passed into it within the captured async context.
171+
172+
```js
173+
const asyncLocalStorage = new AsyncLocalStorage();
174+
const runInAsyncScope = asyncLocalStorage.run(123, () => als.snapshot());
175+
const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
176+
console.log(result) // returns 123
177+
```
178+
179+
AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple async context tracking purposes, for example:
180+
181+
```js
182+
class Foo {
183+
#runInAsyncScope = AsyncLocalStorage.snapshot();
184+
185+
get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
186+
}
187+
188+
const foo = asyncLocalStorage.run(123, () => new Foo());
189+
console.log(asyncLocalStorage.run(321, () => foo.get())) // returns 123
190+
```
191+
150192
### `asyncLocalStorage.disable()`
151193

152194
<!-- YAML

lib/async_hooks.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,14 @@ class AsyncLocalStorage {
288288
this._onPropagate = onPropagate;
289289
}
290290

291+
static bind(fn, thisArg) {
292+
return new AsyncResource('bound-anonymous-fn').bind(fn, thisArg);
293+
}
294+
295+
static snapshot() {
296+
return AsyncLocalStorage.bind((cb, ...args) => cb(...args));
297+
}
298+
291299
disable() {
292300
if (this.enabled) {
293301
this.enabled = false;

0 commit comments

Comments
 (0)