Skip to content

Commit 5fd26d5

Browse files
committed
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
1 parent 689680a commit 5fd26d5

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
@@ -329,20 +329,17 @@ async_hooks.createHook({
329329
},
330330
before(asyncId) {
331331
const indentStr = ' '.repeat(indent);
332-
fs.writeFileSync('log.out',
333-
`${indentStr}before: ${asyncId}\n`, { flag: 'a' });
332+
fs.writeSync(process.stdout.fd, `${indentStr}before: ${asyncId}\n`);
334333
indent += 2;
335334
},
336335
after(asyncId) {
337336
indent -= 2;
338337
const indentStr = ' '.repeat(indent);
339-
fs.writeFileSync('log.out',
340-
`${indentStr}after: ${asyncId}\n`, { flag: 'a' });
338+
fs.writeSync(process.stdout.fd, `${indentStr}after: ${asyncId}\n`);
341339
},
342340
destroy(asyncId) {
343341
const indentStr = ' '.repeat(indent);
344-
fs.writeFileSync('log.out',
345-
`${indentStr}destroy: ${asyncId}\n`, { flag: 'a' });
342+
fs.writeSync(process.stdout.fd, `${indentStr}destroy: ${asyncId}\n`);
346343
},
347344
}).enable();
348345

@@ -378,16 +375,38 @@ the value of the current execution context; which is delineated by calls to
378375
Only using `execution` to graph resource allocation results in the following:
379376

380377
```console
381-
Timeout(7) -> TickObject(6) -> root(1)
378+
root(1)
379+
^
380+
|
381+
TickObject(6)
382+
^
383+
|
384+
Timeout(7)
382385
```
383386

384387
The `TCPSERVERWRAP` is not part of this graph, even though it was the reason for
385388
`console.log()` being called. This is because binding to a port without a host
386389
name is a *synchronous* operation, but to maintain a completely asynchronous
387-
API the user's callback is placed in a `process.nextTick()`.
390+
API the user's callback is placed in a `process.nextTick()`. Which is why
391+
`TickObject` is present in the output and is a 'parent' for `.listen()`
392+
callback.
388393

389394
The graph only shows *when* a resource was created, not *why*, so to track
390-
the *why* use `triggerAsyncId`.
395+
the *why* use `triggerAsyncId`. Which can be represented with the following
396+
graph:
397+
398+
```console
399+
bootstrap(1)
400+
|
401+
˅
402+
TCPSERVERWRAP(5)
403+
|
404+
˅
405+
TickObject(6)
406+
|
407+
˅
408+
Timeout(7)
409+
```
391410

392411
##### `before(asyncId)`
393412

0 commit comments

Comments
 (0)