Skip to content

Commit

Permalink
doc: async_hooks asynchronous content example add mjs code
Browse files Browse the repository at this point in the history
PR-URL: #47401
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
  • Loading branch information
btea authored and MoLow committed Jul 6, 2023
1 parent cb3abda commit 2a682b5
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion doc/api/async_hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,48 @@ The following is an example with additional information about the calls to
callback to `listen()` will look like. The output formatting is slightly more
elaborate to make calling context easier to see.

```js
```mjs
import async_hooks from 'node:async_hooks';
import fs from 'node:fs';
import net from 'node:net';
import { stdout } from 'node:process';
const { fd } = stdout;

let indent = 0;
async_hooks.createHook({
init(asyncId, type, triggerAsyncId) {
const eid = async_hooks.executionAsyncId();
const indentStr = ' '.repeat(indent);
fs.writeSync(
fd,
`${indentStr}${type}(${asyncId}):` +
` trigger: ${triggerAsyncId} execution: ${eid}\n`);
},
before(asyncId) {
const indentStr = ' '.repeat(indent);
fs.writeSync(fd, `${indentStr}before: ${asyncId}\n`);
indent += 2;
},
after(asyncId) {
indent -= 2;
const indentStr = ' '.repeat(indent);
fs.writeSync(fd, `${indentStr}after: ${asyncId}\n`);
},
destroy(asyncId) {
const indentStr = ' '.repeat(indent);
fs.writeSync(fd, `${indentStr}destroy: ${asyncId}\n`);
},
}).enable();

net.createServer(() => {}).listen(8080, () => {
// Let's wait 10ms before logging the server started.
setTimeout(() => {
console.log('>>>', async_hooks.executionAsyncId());
}, 10);
});
```

```cjs
const async_hooks = require('node:async_hooks');
const fs = require('node:fs');
const net = require('node:net');
Expand Down

0 comments on commit 2a682b5

Please sign in to comment.