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


Node.js AsyncLocalStorage.enterWith(store)用法及代碼示例

asyncLocalStorage.enterWith(store)

添加於:v13.11.0、v12.17.0
Stability: 1 - 實驗性

參數

過渡到當前同步執行的剩餘部分的上下文,然後通過任何後續異步調用持久化存儲。

例子:

const store = { id: 1 };
// Replaces previous store with the given store object
asyncLocalStorage.enterWith(store);
asyncLocalStorage.getStore(); // Returns the store object
someAsyncOperation(() => {
  asyncLocalStorage.getStore(); // Returns the same object
});

這種轉變將持續到整個同步執行。這意味著,例如,如果在事件處理程序中輸入上下文,則後續事件處理程序也將在該上下文中運行,除非專門使用 AsyncResource 綁定到另一個上下文。這就是為什麽 run() 應該優先於 enterWith() 的原因,除非有充分的理由使用後一種方法。

const store = { id: 1 };

emitter.on('my-event', () => {
  asyncLocalStorage.enterWith(store);
});
emitter.on('my-event', () => {
  asyncLocalStorage.getStore(); // Returns the same object
});

asyncLocalStorage.getStore(); // Returns undefined
emitter.emit('my-event');
asyncLocalStorage.getStore(); // Returns the same object

相關用法


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