与 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
  });
} 

本例中 store 只在回调函数和 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.