The AsyncLocalStorage
class has been introduced in the Async Hooks module.
This API allows keeping a context across asynchronous operations. For instance, if an sequence id is stored
within an instance of AsyncLocalStorage
for each entering HTTP requests in a server, it will be possible
to retrieve this id without knowing the current HTTP request.
const http = require('http');
const { AsyncLocalStorage } = require('async_hooks');
const asyncLocalStorage = new AsyncLocalStorage();
function logWithId(msg) {
const id = asyncLocalStorage.getStore();
console.log(`${id !== undefined ? id : '-'}:`, msg);
}
let idSeq = 0;
http.createServer((req, res) => {
asyncLocalStorage.run(idSeq++, () => {
logWithId('start');
// Imagine any chain of async operations here
setImmediate(() => {
logWithId('finish');
res.end();
});
});
}).listen(8080);
In this example, the logWithId
function, will always know what the current request id is.
Use cases of this API include:
- logging
- User identification
- Performance tracking
- Error trancking and handling
- much more!
Note: This API is still experimental and some methods might change in the next releases of Node.js