Skip to content

Commit fce0272

Browse files
committed
doc: improve AsyncLocalStorage sample
PR-URL: nodejs#32757 Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: Chengzhong Wu <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Gerhard Stöbich <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent c6f7f55 commit fce0272

File tree

1 file changed

+24
-25
lines changed

1 file changed

+24
-25
lines changed

doc/api/async_hooks.md

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -869,41 +869,40 @@ chains. It allows storing data throughout the lifetime of a web request
869869
or any other asynchronous duration. It is similar to thread-local storage
870870
in other languages.
871871

872-
The following example builds a logger that will always know the current HTTP
873-
request and uses it to display enhanced logs without needing to explicitly
874-
provide the current HTTP request to it.
872+
The following example uses `AsyncLocalStorage` to build a simple logger
873+
that assigns IDs to incoming HTTP requests and includes them in messages
874+
logged within each request.
875875

876876
```js
877-
const { AsyncLocalStorage } = require('async_hooks');
878877
const http = require('http');
878+
const { AsyncLocalStorage } = require('async_hooks');
879879

880-
const kReq = 'CURRENT_REQUEST';
881880
const asyncLocalStorage = new AsyncLocalStorage();
882881

883-
function log(...args) {
884-
const store = asyncLocalStorage.getStore();
885-
// Make sure the store exists and it contains a request.
886-
if (store && store.has(kReq)) {
887-
const req = store.get(kReq);
888-
// Prints `GET /items ERR could not do something
889-
console.log(req.method, req.url, ...args);
890-
} else {
891-
console.log(...args);
892-
}
882+
function logWithId(msg) {
883+
const id = asyncLocalStorage.getStore();
884+
console.log(`${id !== undefined ? id : '-'}:`, msg);
893885
}
894886

895-
http.createServer((request, response) => {
896-
asyncLocalStorage.run(new Map(), () => {
897-
const store = asyncLocalStorage.getStore();
898-
store.set(kReq, request);
899-
someAsyncOperation((err, result) => {
900-
if (err) {
901-
log('ERR', err.message);
902-
}
887+
let idSeq = 0;
888+
http.createServer((req, res) => {
889+
asyncLocalStorage.run(idSeq++, () => {
890+
logWithId('start');
891+
// Imagine any chain of async operations here
892+
setImmediate(() => {
893+
logWithId('finish');
894+
res.end();
903895
});
904896
});
905-
})
906-
.listen(8080);
897+
}).listen(8080);
898+
899+
http.get('http://localhost:8080');
900+
http.get('http://localhost:8080');
901+
// Prints:
902+
// 0: start
903+
// 1: start
904+
// 0: finish
905+
// 1: finish
907906
```
908907

909908
When having multiple instances of `AsyncLocalStorage`, they are independent

0 commit comments

Comments
 (0)