0 day streak
javascript / expert
Snippet

Manual Context Tracking with AsyncResource

While AsyncLocalStorage is the standard for context, AsyncResource provides low-level control for manual context propagation. It is essential when integrating with legacy libraries or event-driven systems where the execution flow doesn't automatically preserve the asynchronous context.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import { AsyncResource } from 'node:async_hooks';
class DatabaseQuery extends AsyncResource {
constructor(queryId) {
super('DB_QUERY');
this.queryId = queryId;
}
run(callback) {
this.runInAsyncScope(callback);
}
}
const query = new DatabaseQuery('req-123');
query.run(() => {
// Async context is now preserved even through legacy callbacks
});
nodejs
Breakdown
1
super('DB_QUERY')
Initializes the async resource with a custom type for monitoring and debugging.
2
this.runInAsyncScope(callback)
Executes the callback within the asynchronous context associated with this specific resource instance.