From 45d2f4dd3c0c9d2c6341be441ef3fc6aff46a7a6 Mon Sep 17 00:00:00 2001 From: James M Snell Date: Thu, 30 Jul 2020 19:53:32 -0700 Subject: [PATCH] async_hooks: add AsyncResource.bind utility MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 Reviewed-By: Gus Caplan Reviewed-By: Matteo Collina Reviewed-By: Andrey Pechkurov Reviewed-By: Gerhard Stöbich --- doc/api/async_hooks.md | 36 ++++++++++++++++++++---- lib/async_hooks.js | 24 ++++++++++++++++ test/parallel/test-asyncresource-bind.js | 35 +++++++++++++++++++++++ 3 files changed, 90 insertions(+), 5 deletions(-) create mode 100644 test/parallel/test-asyncresource-bind.js diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index 8080e628617bde..a812f6998457f3 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -733,6 +733,32 @@ class DBQuery extends AsyncResource { } ``` +#### `static AsyncResource.bind(fn[, type])` + + +* `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)` + + +* `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])`