AsyncLocalStorage Keeps Request Context
Propagate per-request data through deep awaits with AsyncLocalStorage: each requestContext.run gets an isolated store reachable anywhere inside.
Code
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());Output
Captured from a sandboxed run of this snippet in the build pipeline.
done: req-1 | done: req-2 | done: req-3
outside: undefinedWhat the code does
AsyncLocalStorage Keeps Request Context is built around the function handle.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The only import source is node:async_hooks, a Node.js built-in, exposing AsyncLocalStorage.
Caveats
node:async_hooksresolves inside Node.js without any package — it is a core module.
Using it
The entry-point signature is function handle(requestId, delayMs)
Expect labeled output — outside: — when the file runs.
Key statements
await new Promise((resolve) => setTimeout(resolve, delayMs));
return 'done: ' + id;
Interactive Tools for This Topic
HTTP Request Builder & cURLBuild HTTP requests with method, URL, headers, and body, then generate the equivalent cURL command. Supports GET, POST, PUT, DELETE, and PATCH with custom headers.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does this import from outside the project?
- Only `node:async_hooks`, and that is a Node.js built-in — it comes with the runtime.
Report a problem with this exampleOpens a pre-filled issue on GitHub.