Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/nodejs/node.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJames M Snell <jasnell@gmail.com>2020-07-31 05:53:32 +0300
committerJames M Snell <jasnell@gmail.com>2020-08-04 04:40:16 +0300
commit74df7496ff6d899e4b8ceed9505a641e79ad6366 (patch)
tree3eb2adfbf0228678c62447c2880d26c053507f15 /doc/api/async_hooks.md
parent744a284ccc943d352fd2cc15e35aaf720b1139ae (diff)
async_hooks: add AsyncResource.bind utility
Creates an internal AsyncResource and binds a function to it, ensuring that the function is invoked within execution context in which bind was called. PR-URL: https://github.com/nodejs/node/pull/34574 Reviewed-By: Stephen Belanger <admin@stephenbelanger.com> Reviewed-By: Gus Caplan <me@gus.host> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Andrey Pechkurov <apechkurov@gmail.com> Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
Diffstat (limited to 'doc/api/async_hooks.md')
-rw-r--r--doc/api/async_hooks.md36
1 files changed, 31 insertions, 5 deletions
diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md
index f980b237b11..ebab01f6f79 100644
--- a/doc/api/async_hooks.md
+++ b/doc/api/async_hooks.md
@@ -729,6 +729,32 @@ class DBQuery extends AsyncResource {
}
```
+#### `static AsyncResource.bind(fn[, type])`
+<!-- YAML
+added: REPLACEME
+-->
+
+* `fn` {Function} The function to bind to the current execution context.
+* `type` {string} An optional name to associate with the underlying
+ `AsyncResource`.
+
+Binds the given function to the current execution context.
+
+The returned function will have an `asyncResource` property referencing
+the `AsyncResource` to which the function is bound.
+
+#### `asyncResource.bind(fn)`
+<!-- YAML
+added: REPLACEME
+-->
+
+* `fn` {Function} The function to bind to the current `AsyncResource`.
+
+Binds the given function to execute to this `AsyncResource`'s scope.
+
+The returned function will have an `asyncResource` property referencing
+the `AsyncResource` to which the function is bound.
+
#### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])`
<!-- YAML
added: v9.6.0
@@ -900,12 +926,12 @@ const { createServer } = require('http');
const { AsyncResource, executionAsyncId } = require('async_hooks');
const server = createServer((req, res) => {
- const asyncResource = new AsyncResource('request');
- // The listener will always run in the execution context of `asyncResource`.
- req.on('close', asyncResource.runInAsyncScope.bind(asyncResource, () => {
- // Prints: true
- console.log(asyncResource.asyncId() === executionAsyncId());
+ req.on('close', AsyncResource.bind(() => {
+ // Execution context is bound to the current outer scope.
}));
+ req.on('close', () => {
+ // Execution context is bound to the scope that caused 'close' to emit.
+ });
res.end();
}).listen(3000);
```