From 23a54a479cd0f5d09154c9bc33dd77555f10c328 Mon Sep 17 00:00:00 2001 From: flakey5 <73616808+flakey5@users.noreply.github.com> Date: Fri, 27 Jan 2023 17:12:00 -0800 Subject: [PATCH] lib: AsyncLocalStorage.bind() and AsyncLocalStorage.snapshot() --- doc/api/async_context.md | 44 ++++++++++++++++++++++++++++++++++++++++ lib/async_hooks.js | 8 ++++++++ 2 files changed, 52 insertions(+) diff --git a/doc/api/async_context.md b/doc/api/async_context.md index 51092f25dcfccf..c7052215f9fb54 100644 --- a/doc/api/async_context.md +++ b/doc/api/async_context.md @@ -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])` + + + +* `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()` + + + +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()`