Skip to content

Commit 146538d

Browse files
lundibundiMylesBorins
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 e378b68 commit 146538d

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
@@ -331,20 +331,17 @@ async_hooks.createHook({
331331
},
332332
before(asyncId) {
333333
const indentStr = ' '.repeat(indent);
334-
fs.writeFileSync('log.out',
335-
`${indentStr}before: ${asyncId}\n`, { flag: 'a' });
334+
fs.writeSync(process.stdout.fd, `${indentStr}before: ${asyncId}\n`);
336335
indent += 2;
337336
},
338337
after(asyncId) {
339338
indent -= 2;
340339
const indentStr = ' '.repeat(indent);
341-
fs.writeFileSync('log.out',
342-
`${indentStr}after: ${asyncId}\n`, { flag: 'a' });
340+
fs.writeSync(process.stdout.fd, `${indentStr}after: ${asyncId}\n`);
343341
},
344342
destroy(asyncId) {
345343
const indentStr = ' '.repeat(indent);
346-
fs.writeFileSync('log.out',
347-
`${indentStr}destroy: ${asyncId}\n`, { flag: 'a' });
344+
fs.writeSync(process.stdout.fd, `${indentStr}destroy: ${asyncId}\n`);
348345
},
349346
}).enable();
350347

@@ -380,16 +377,38 @@ the value of the current execution context; which is delineated by calls to
380377
Only using `execution` to graph resource allocation results in the following:
381378

382379
```console
383-
Timeout(7) -> TickObject(6) -> root(1)
380+
root(1)
381+
^
382+
|
383+
TickObject(6)
384+
^
385+
|
386+
Timeout(7)
384387
```
385388

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

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

394413
##### `before(asyncId)`
395414

0 commit comments

Comments
 (0)