← 中文资源

简体中文版本

AsyncLocalStorage 保持请求上下文

AsyncLocalStorage 给每个请求挂独立上下文:run 内任何深度的 await 都能读回自己的 requestId,作用域之外 getStore() 返回 undefined。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

done: req-1 | done: req-2 | done: req-3
outside: undefined

实现说明

底层就是函数 handle。 每个异步步骤都被 await,拒绝会在发起调用的那一行浮出。唯一的导入来源是 node:async_hooks(Node.js 内建),暴露出 AsyncLocalStorage。

使用要点

  • node:async_hooks 是 Node.js 内建模块——随运行时自带,无需安装。
  • 跑完文件,输出里会留下标记——outside:。

常见问题

它从项目之外导入了什么?

只有 node:async_hooks,而它是 Node.js 内建的——随运行时提供。

主签名形如 function handle(requestId, delayMs)

核心语句

await new Promise((resolve) => setTimeout(resolve, delayMs));
return 'done: ' + id;

代码示例

import { AsyncLocalStorage } from 'node:async_hooks';

const requestContext = new AsyncLocalStorage();

// 每个请求挂独立上下文:run 内任何深度的 await 都能读回自己的 store
function handle(requestId, delayMs) {
  return requestContext.run({ requestId }, async () => {
    await new Promise((resolve) => setTimeout(resolve, delayMs));
    const { requestId: id } = requestContext.getStore();
    return 'done: ' + id;
  });
}

// Promise.all 保持调用顺序,与完成先后无关
const jobs = [handle('req-1', 30), handle('req-2', 10), handle('req-3', 20)];
console.log((await Promise.all(jobs)).join(' | '));

// run 作用域之外读不到存储:getStore() 返回 undefined
console.log('outside:', requestContext.getStore());