Skip to main content
AsyncLocalStorage.snapshot - async_hooks - Node documentation
method AsyncLocalStorage.snapshot
Unstable

Usage in Deno

import { AsyncLocalStorage } from "node:async_hooks";
AsyncLocalStorage.snapshot(): <
R,
TArgs extends any[],
>
(
fn: (...args: TArgs) => R,
...args: TArgs,
) => R

Captures the current execution context and returns a function that accepts a function as an argument. Whenever the returned function is called, it calls the function passed to it within the captured context.

const asyncLocalStorage = new AsyncLocalStorage();
const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.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:

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

Return Type

<
R,
TArgs extends any[],
>
(
fn: (...args: TArgs) => R,
...args: TArgs,
) => R

A new function with the signature (fn: (...args) : R, ...args) : R.