Skip to content

Commit f12c6f4

Browse files
lundibundiaddaleax
authored andcommitted
doc: improve async_hooks asynchronous context example
* use writeFile(1) everywhere to log * prettify execution id graph * add clearer explanation for TickObject presence * add causation graph via triggerAsyncId PR-URL: #33730 Reviewed-By: Gerhard Stöbich <[email protected]> Reviewed-By: Andrey Pechkurov <[email protected]> Reviewed-By: James M Snell <[email protected]> Reviewed-By: Vladimir de Turckheim <[email protected]>
1 parent 8fb265d commit f12c6f4

File tree

1 file changed

+28
-9
lines changed

1 file changed

+28
-9
lines changed

doc/api/async_hooks.md

Lines changed: 28 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -336,20 +336,17 @@ async_hooks.createHook({
336336
},
337337
before(asyncId) {
338338
const indentStr = ' '.repeat(indent);
339-
fs.writeFileSync('log.out',
340-
`${indentStr}before: ${asyncId}\n`, { flag: 'a' });
339+
fs.writeSync(process.stdout.fd, `${indentStr}before: ${asyncId}\n`);
341340
indent += 2;
342341
},
343342
after(asyncId) {
344343
indent -= 2;
345344
const indentStr = ' '.repeat(indent);
346-
fs.writeFileSync('log.out',
347-
`${indentStr}after: ${asyncId}\n`, { flag: 'a' });
345+
fs.writeSync(process.stdout.fd, `${indentStr}after: ${asyncId}\n`);
348346
},
349347
destroy(asyncId) {
350348
const indentStr = ' '.repeat(indent);
351-
fs.writeFileSync('log.out',
352-
`${indentStr}destroy: ${asyncId}\n`, { flag: 'a' });
349+
fs.writeSync(process.stdout.fd, `${indentStr}destroy: ${asyncId}\n`);
353350
},
354351
}).enable();
355352

@@ -385,16 +382,38 @@ the value of the current execution context; which is delineated by calls to
385382
Only using `execution` to graph resource allocation results in the following:
386383

387384
```console
388-
Timeout(7) -> TickObject(6) -> root(1)
385+
root(1)
386+
^
387+
|
388+
TickObject(6)
389+
^
390+
|
391+
Timeout(7)
389392
```
390393

391394
The `TCPSERVERWRAP` is not part of this graph, even though it was the reason for
392395
`console.log()` being called. This is because binding to a port without a host
393396
name is a *synchronous* operation, but to maintain a completely asynchronous
394-
API the user's callback is placed in a `process.nextTick()`.
397+
API the user's callback is placed in a `process.nextTick()`. Which is why
398+
`TickObject` is present in the output and is a 'parent' for `.listen()`
399+
callback.
395400

396401
The graph only shows *when* a resource was created, not *why*, so to track
397-
the *why* use `triggerAsyncId`.
402+
the *why* use `triggerAsyncId`. Which can be represented with the following
403+
graph:
404+
405+
```console
406+
bootstrap(1)
407+
|
408+
˅
409+
TCPSERVERWRAP(5)
410+
|
411+
˅
412+
TickObject(6)
413+
|
414+
˅
415+
Timeout(7)
416+
```
398417

399418
##### `before(asyncId)`
400419

0 commit comments

Comments
 (0)