當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js AsyncLocalStorage.run(store, callback[, ...args])用法及代碼示例

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

添加於:v13.10.0、v12.17.0

參數

在上下文中同步運行函數並返回其返回值。在回調函數之外無法訪問商店。在回調中創建的任何異步操作都可以訪問存儲。

可選的args 被傳遞給回調函數。

如果回調函數拋出錯誤,錯誤也會由run() 拋出。堆棧跟蹤不受此調用的影響,並且退出上下文。

例子:

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
}

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 AsyncLocalStorage.run(store, callback[, ...args])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。