From 74df7496ff6d899e4b8ceed9505a641e79ad6366 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 f980b237b11c6e..ebab01f6f79ed4 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])` + + +* `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])`