AsyncLocalStorage.prototype.run - Node documentation
method AsyncLocalStorage.prototype.run

Usage in Deno

import { AsyncLocalStorage } from "node:async_hooks";
AsyncLocalStorage.prototype.run<R>(
store: T,
callback: () => R,
): R

Runs a function synchronously within a context and returns its return value. The store is not accessible outside of the callback function. The store is accessible to any asynchronous operations created within the callback.

The optional args are passed to the callback function.

If the callback function throws an error, the error is thrown by run() too. The stacktrace is not impacted by this call and the context is exited.

Example:

const store = { id: 2 };
try {
  asyncLocalStorage.run(store, () => {
    asyncLocalStorage.getStore(); // Returns the store object
    setTimeout(() => {
      asyncLocalStorage.getStore(); // Returns the store object
    }, 200);
    throw new Error();
  });
} catch (e) {
  asyncLocalStorage.getStore(); // Returns undefined
  // The error will be caught here
}

Type Parameters

R

Parameters

store: T
callback: () => R

Return Type

R
AsyncLocalStorage.prototype.run<
R,
TArgs extends any[],
>
(
store: T,
callback: (...args: TArgs) => R,
...args: TArgs,
): R

Type Parameters

R
TArgs extends any[]

Parameters

store: T
callback: (...args: TArgs) => R
...args: TArgs

Return Type

R