javascript / expert
Snippet
Request Context via AsyncLocalStorage
AsyncLocalStorage provides a way to store data throughout the lifetime of an asynchronous operation (like an HTTP request). It eliminates 'prop drilling' by allowing functions deep in the call stack to access context-specific data without it being explicitly passed as an argument.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { AsyncLocalStorage } from 'node:async_hooks';const als = new AsyncLocalStorage();function logWithId(msg) {const id = als.getStore();console.log(`[Request ${id}] ${msg}`);}als.run('REQ_123', () => {setImmediate(() => logWithId('Finished processing'));});
nodejs
Breakdown
1
als.run('REQ_123', () => { ... });
Starts an async scope where the value 'REQ_123' is associated with all nested calls.
2
als.getStore();
Retrieves the value associated with the current asynchronous execution context.