asyncLocalStorage.run(store, callback[, ...args])


在上下文中同步运行一个函数并返回其返回值。存储在回调函数外不可访问。存储可以被回调函数内创建的任何异步操作访问。

【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.】

可选的 args 会传递给回调函数。

【The optional args are passed to the callback function.】

如果回调函数抛出错误,run() 也会抛出该错误。堆栈跟踪不会受到此调用的影响,并且上下文会被退出。

【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
}