async/await 的使用
🌐 Usage with async/await
如果在异步函数中,只有一个 await 调用需要在某个上下文中运行,应使用以下模式:
🌐 If, within an async function, only one await call is to run within a context,
the following pattern should be used:
async function fn() {
await asyncLocalStorage.run(new Map(), () => {
asyncLocalStorage.getStore().set('key', value);
return foo(); // The return value of foo will be awaited
});
} 在这个例子中,该存储仅在回调函数以及 foo 调用的函数中可用。在 run 外部,调用 getStore 将返回 undefined。
🌐 In this example, the store is only available in the callback function and the
functions called by foo. Outside of run, calling getStore will return
undefined.