Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit a8e0772

Browse files
committedJan 28, 2023
lib: AsyncLocalStorage.bind() and AsyncLocalStorage.snapshot()
1 parent 19bcba0 commit a8e0772

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
 

‎doc/api/async_context.md

+44
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,50 @@ 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+
### Static method: `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+
### Static method: `AsyncLocalStorage.snapshot()`
165+
166+
<!-- YAML
167+
added: REPLACEME
168+
-->
169+
170+
Returns a callback that captures the current async context and invokes a
171+
callback passed into it within the captured async context.
172+
173+
```js
174+
const asyncLocalStorage = new AsyncLocalStorage();
175+
const runInAsyncScope = asyncLocalStorage.run(123, () => als.snapshot());
176+
const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
177+
console.log(result); // returns 123
178+
```
179+
180+
AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
181+
async context tracking purposes, for example:
182+
183+
```js
184+
class Foo {
185+
#runInAsyncScope = AsyncLocalStorage.snapshot();
186+
187+
get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
188+
}
189+
190+
const foo = asyncLocalStorage.run(123, () => new Foo());
191+
console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
192+
```
193+
150194
### `asyncLocalStorage.disable()`
151195

152196
<!-- YAML

‎lib/async_hooks.js

+8
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)
Please sign in to comment.