asyncLocalStorage.run(store, callback[, ...args])
-
store
<any> -
callback
<Function> -
...args
<any>
在上下文中同步运行函数并返回其返回值。在回调函数之外无法访问该存储。在回调中创建的任何异步操作都可以访问该存储。
¥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
}