静态方法:AsyncLocalStorage.snapshot()


【Static method: AsyncLocalStorage.snapshot()

  • 返回值:<Function> 一个新的函数,其签名为 (fn: (...args) : R, ...args) : 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() 可以用于替代 AsyncResource,以实现简单的异步上下文跟踪,例如:

【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