11# Async Hooks
22
3-
43> Stability: 1 - Experimental
54
6-
75The ` async-hooks ` module provides an API to register callbacks tracking the
86lifetime of asynchronous resources created inside a Node.js application.
7+ It can be accessed using ` require('async-hooks') ` .
98
109## Terminology
1110
12- An async resource represents either a "handle" or a "request" .
11+ An async resource represents either a _ handle _ or a _ request _ .
1312
1413Handles are a reference to a system resource. Some resources are a simple
1514identifier. For example, file system handles are represented by a file
@@ -27,7 +26,7 @@ writing data to disk.
2726
2827### Overview
2928
30- Here is a simple overview of the public API. All of this API is explained in
29+ Following is a simple overview of the public API. All of this API is explained in
3130more detail further down.
3231
3332``` js
@@ -38,7 +37,7 @@ const cid = async_hooks.currentId();
3837
3938// Return the id of the handle responsible for triggering the callback of the
4039// current execution scope to fire.
41- const tid = aysnc_hooks .triggerId ();
40+ const tid = async_hooks .triggerId ();
4241
4342// Create a new AsyncHook instance. All of these callbacks are optional.
4443const asyncHook = async_hooks .createHook ({ init, before, after, destroy });
@@ -78,6 +77,12 @@ function destroy(id) { }
7877
7978#### ` async_hooks.createHook(callbacks) `
8079
80+ <!-- YAML
81+ added: REPLACEME
82+ -->
83+
84+ * ` callbacks ` {Object} the callbacks to register
85+
8186Registers functions to be called for different lifetime events of each async
8287operation.
8388The callbacks ` init() ` /` before() ` /` after() ` /` destroy() ` are registered via an
@@ -87,14 +92,16 @@ lifetime of the `AsyncWrap` C++ class. These callbacks will also be called to
8792emulate the lifetime of handles and requests that do not fit this model. For
8893example, ` HTTPParser ` instances are recycled to improve performance. Therefore the
8994` destroy() ` callback is called manually after a connection is done using
90- it, just before it's placed back into the unused resource pool.
95+ it, just before it is placed back into the unused resource pool.
9196
9297All callbacks are optional. So, for example, if only resource cleanup needs to
9398be tracked then only the ` destroy() ` callback needs to be passed. The
9499specifics of all functions that can be passed to ` callbacks ` is in the section
95100` Hook Callbacks ` .
96101
97- ** Error Handling** : If any ` AsyncHook ` callbacks throw, the application will
102+ ##### Error Handling
103+
104+ If any ` AsyncHook ` callbacks throw, the application will
98105print the stack trace and exit. The exit path does follow that of any uncaught
99106exception. However ` 'exit' ` callbacks will still fire unless the application
100107is run with ` --abort-on-uncaught-exception ` , in which case a stack trace will
@@ -141,7 +148,7 @@ destructor calls are emulated.
141148##### ` init(id, type, triggerId, resource) `
142149
143150* ` id ` {number} a unique id for the async resource
144- * ` type ` {String } the type of the async resource
151+ * ` type ` {string } the type of the async resource
145152* ` triggerId ` {number} the unique id of the async resource in whose
146153 execution context this async resource was created
147154* ` resource ` {Object} reference to the resource representing the async operation,
@@ -169,7 +176,7 @@ The `type` is a String that represents the type of resource that caused
169176Some examples include ` TCP ` , ` GetAddrInfo ` and ` HTTPParser ` . Users will be able
170177to define their own ` type ` when using the public embedder API.
171178
172- ** Note:* * It is possible to have type name collisions. Embedders are recommended
179+ * Note:* It is possible to have type name collisions. Embedders are recommended
173180to use unique prefixes per module to prevent collisions when listening to the
174181hooks.
175182
@@ -181,7 +188,7 @@ The following is a simple demonstration of this:
181188``` js
182189const async_hooks = require (' async_hooks' );
183190
184- asyns_hooks .createHook ({
191+ async_hooks .createHook ({
185192 init (id , type , triggerId ) {
186193 const cId = async_hooks .currentId ();
187194 process ._rawDebug (` ${ type} (${ id} ): trigger: ${ triggerId} scope: ${ cId} ` );
@@ -272,13 +279,13 @@ First notice that `scope` and the value returned by `currentId()` are always
272279the same. That's because ` currentId() ` simply returns the value of the
273280current execution context; which is defined by ` before() ` and ` after() ` calls.
274281
275- Now if we only use ` scope ` to graph resource allocation we get the following:
282+ Now only using ` scope ` to graph resource allocation results in the following:
276283
277284```
278285TTYWRAP(6) -> Timeout(4) -> TIMERWRAP(5) -> TickObject(3) -> root(1)
279286```
280287
281- The ` TCPWRAP ` isn't part of this graph; evne though it was the reason for
288+ The ` TCPWRAP ` isn't part of this graph; even though it was the reason for
282289` console.log() ` being called. This is because binding to a port without a
283290hostname is actually synchronous, but to maintain a completely asynchronous API
284291the user's callback is placed in a ` process.nextTick() ` .
@@ -323,9 +330,9 @@ Some resources, such as `HTTPParser`, are not actually destructed but instead
323330placed in an unused resource pool to be used later. For these ` destroy() ` will
324331be called just before the resource is placed on the unused resource pool.
325332
326- ** Note:* * Some resources depend on GC for cleanup. So if a reference is made to
333+ * Note:* Some resources depend on GC for cleanup. So if a reference is made to
327334the ` resource ` object passed to ` init() ` it's possible that ` destroy() ` is
328- never called. Causing a memory leak in the application. Of course if you know
335+ never called. Causing a memory leak in the application. Of course if
329336the resource doesn't depend on GC then this isn't an issue.
330337
331338#### ` async_hooks.currentId() `
@@ -343,17 +350,17 @@ fs.open(path, (err, fd) => {
343350```
344351
345352It is important to note that the id returned fom ` currentId() ` is related to
346- execution timing. Not causality (which is covered by ` triggerId() ` ). For
353+ execution timing. Not causality (which is covered by ` triggerId() ` ). For
347354example:
348355
349356``` js
350- const server = net .createServer (function onconnection (conn ) {
357+ const server = net .createServer (function onConnection (conn ) {
351358 // Returns the id of the server, not of the new connection. Because the
352359 // on connection callback runs in the execution scope of the server's
353360 // MakeCallback().
354361 async_hooks .currentId ();
355362
356- }).listen (port, function onlistening () {
363+ }).listen (port, function onListening () {
357364 // Returns the id of a TickObject (i.e. process.nextTick()) because all
358365 // callbacks passed to .listen() are wrapped in a nextTick().
359366 async_hooks .currentId ();
@@ -390,7 +397,7 @@ this a JavaScript API is provided.
390397
391398### ` class AsyncEvent() `
392399
393- The class ` AsyncEvent ` was designed to be extended from for embedder's async
400+ The class ` AsyncEvent ` was designed to be extended by the embedder's async
394401resources. Using this users can easily trigger the lifetime events of their
395402own resources.
396403
@@ -424,7 +431,7 @@ asyncEvent.triggerId();
424431#### ` AsyncEvent(type[, triggerId]) `
425432
426433* arguments
427- * ` type ` {String } the type of ascycn event
434+ * ` type ` {string } the type of ascycn event
428435 * ` triggerId ` {number} the id of the execution context that created this async
429436 event
430437* Returns {AsyncEvent} A reference to ` asyncHook ` .
@@ -433,7 +440,7 @@ Example usage:
433440
434441``` js
435442class DBQuery extends AsyncEvent {
436- construtor (db ) {
443+ constructor (db ) {
437444 this .db = db;
438445 }
439446
@@ -454,15 +461,15 @@ class DBQuery extends AsyncEvent {
454461
455462#### ` asyncEvent.emitBefore() `
456463
457- * Returns {Undefined }
464+ * Returns {undefined }
458465
459466Call all ` before() ` hooks and let them know a new asynchronous execution
460467context is being entered. If nested calls to ` emitBefore() ` are made the stack
461468of ` id ` s will be tracked and properly unwound.
462469
463470#### ` asyncEvent.emitAfter() `
464471
465- * Returns {Undefined }
472+ * Returns {undefined }
466473
467474Call all ` after() ` hooks. If nested calls to ` emitBefore() ` were made then make
468475sure the stack is unwound properly. Otherwise an error will be thrown.
@@ -474,7 +481,7 @@ this.
474481
475482#### ` asyncEvent.emitDestroy() `
476483
477- * Returns {Undefined }
484+ * Returns {undefined }
478485
479486Call all ` destroy() ` hooks. This should only ever be called once. An error will
480487be thrown if it is called more than once. This ** must** be manually called. If
@@ -556,10 +563,10 @@ responsible for the newly created resource being instantiated. For example:
556563#### ` async_hooks.emitInit(id, type[, triggerId][, resource]) `
557564
558565* ` id ` {number} Generated by calling ` newId() `
559- * ` type ` {String }
566+ * ` type ` {string }
560567* ` triggerId ` {number} ** Default:** ` currentId() `
561568* ` resource ` {Object}
562- * Returns {Undefined }
569+ * Returns {undefined }
563570
564571Emit that a resource is being initialized. ` id ` should be a value returned by
565572` async_hooks.newId() ` . Usage will probably be as follows:
@@ -585,7 +592,7 @@ constructor.
585592
586593* ` id ` {number} Generated by ` newId() `
587594* ` triggerId ` {number}
588- * Returns {Undefined }
595+ * Returns {undefined }
589596
590597Notify ` before() ` hooks that the resource is about to enter its execution call
591598stack. If the ` triggerId ` of the resource is different from ` id ` then pass
@@ -610,7 +617,7 @@ MyThing.prototype.done = function done() {
610617#### ` async_hooks.emitAfter(id) `
611618
612619* ` id ` {number} Generated by ` newId() `
613- * Returns {Undefined }
620+ * Returns {undefined }
614621
615622Notify ` after() ` hooks that the resource is exiting its execution call stack.
616623
@@ -629,23 +636,23 @@ after # Foo <- Should be called after Bar
629636after # Bar
630637```
631638
632- ** Note:* * It is not necessary to wrap the callback in a try/finally and force
639+ * Note:* It is not necessary to wrap the callback in a try/finally and force
633640emitAfter() if the callback throws. That is automatically handled by the
634641fatal exception handler.
635642
636643#### ` async_hooks.emitDestroy(id) `
637644
638645* ` id ` {number} Generated by ` newId() `
639- * Returns {Undefined }
646+ * Returns {undefined }
640647
641- Notify hooks that a resource is being destroyed (or being moved to the free'd
648+ Notify hooks that a resource is being destroyed (or being moved to the freed
642649resource pool).
643650
644651#### ` async_hooks.triggerIdScope(triggerId, callback) `
645652
646653* ` triggerId ` {number}
647654* ` callback ` {Function}
648- * Returns {Undefined }
655+ * Returns {undefined }
649656
650657All resources created during the execution of ` callback ` will be given
651658` triggerId ` . Unless it was otherwise 1) passed in as an argument to
0 commit comments