Skip to content

Commit

Permalink
lib: AsyncLocalStorage.bind() and AsyncLocalStorage.snapshot()
Browse files Browse the repository at this point in the history
  • Loading branch information
flakey5 committed Jan 28, 2023
1 parent 19bcba0 commit 23a54a4
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 0 deletions.
44 changes: 44 additions & 0 deletions doc/api/async_context.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,50 @@ this time will print the stack trace and exit. See
Creating an async resource within the `onPropagate` callback will result in
a recursive call to `onPropagate`.

### `asyncLocalStorage.bind(fn [, thisArg])`

<!-- YAML
added: REPLACEME
-->

* `fn` {Function} The function to bind to the current execution context.
* `thisArg` {any}

Binds the given function to the current execution context.

The returned function will have an `asyncResource` property referencing
the `AsyncResource` to which the function is bound.

### `asyncLocalStorage.snapshot()`

<!-- YAML
added: REPLACEME
-->

Returns a callback that captures the current async context and invokes a
callback passed into it within the captured async context.

```js
const asyncLocalStorage = new AsyncLocalStorage();
const runInAsyncScope = asyncLocalStorage.run(123, () => als.snapshot());
const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore()));
console.log(result); // returns 123
```

AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple
async context tracking purposes, for example:

```js
class Foo {
#runInAsyncScope = AsyncLocalStorage.snapshot();

get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); }
}

const foo = asyncLocalStorage.run(123, () => new Foo());
console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123
```

### `asyncLocalStorage.disable()`

<!-- YAML
Expand Down
8 changes: 8 additions & 0 deletions lib/async_hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,14 @@ class AsyncLocalStorage {
this._onPropagate = onPropagate;
}

static bind(fn, thisArg) {
return new AsyncResource('bound-anonymous-fn').bind(fn, thisArg);
}

static snapshot() {
return AsyncLocalStorage.bind((cb, ...args) => cb(...args));
}

disable() {
if (this.enabled) {
this.enabled = false;
Expand Down

0 comments on commit 23a54a4

Please sign in to comment.