Skip to content

Commit c5c40a8

Browse files
bteatargos
authored andcommitted
doc: async_hooks asynchronous content example add mjs code
PR-URL: #47401 Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
1 parent 4431df7 commit c5c40a8

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

doc/api/async_hooks.md

+42-1
Original file line numberDiff line numberDiff line change
@@ -445,7 +445,48 @@ The following is an example with additional information about the calls to
445445
callback to `listen()` will look like. The output formatting is slightly more
446446
elaborate to make calling context easier to see.
447447

448-
```js
448+
```mjs
449+
import async_hooks from 'node:async_hooks';
450+
import fs from 'node:fs';
451+
import net from 'node:net';
452+
import { stdout } from 'node:process';
453+
const { fd } = stdout;
454+
455+
let indent = 0;
456+
async_hooks.createHook({
457+
init(asyncId, type, triggerAsyncId) {
458+
const eid = async_hooks.executionAsyncId();
459+
const indentStr = ' '.repeat(indent);
460+
fs.writeSync(
461+
fd,
462+
`${indentStr}${type}(${asyncId}):` +
463+
` trigger: ${triggerAsyncId} execution: ${eid}\n`);
464+
},
465+
before(asyncId) {
466+
const indentStr = ' '.repeat(indent);
467+
fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`);
468+
indent += 2;
469+
},
470+
after(asyncId) {
471+
indent -= 2;
472+
const indentStr = ' '.repeat(indent);
473+
fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`);
474+
},
475+
destroy(asyncId) {
476+
const indentStr = ' '.repeat(indent);
477+
fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`);
478+
},
479+
}).enable();
480+
481+
net.createServer(() => {}).listen(8080, () => {
482+
// Let's wait 10ms before logging the server started.
483+
setTimeout(() => {
484+
console.log('>>>', async_hooks.executionAsyncId());
485+
}, 10);
486+
});
487+
```
488+
489+
```cjs
449490
const async_hooks = require('node:async_hooks');
450491
const fs = require('node:fs');
451492
const net = require('node:net');

0 commit comments

Comments
 (0)