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>
This commit is contained in:
James M Snell 2020-07-30 19:53:32 -07:00
parent 744a284ccc
commit 74df7496ff
3 changed files with 90 additions and 5 deletions

View file

@ -2,6 +2,7 @@
const {
NumberIsSafeInteger,
ObjectDefineProperties,
ReflectApply,
Symbol,
} = primordials;
@ -9,6 +10,7 @@ const {
const {
ERR_ASYNC_CALLBACK,
ERR_ASYNC_TYPE,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ASYNC_ID
} = require('internal/errors').codes;
const { validateString } = require('internal/validators');
@ -211,6 +213,28 @@ class AsyncResource {
triggerAsyncId() {
return this[trigger_async_id_symbol];
}
bind(fn) {
if (typeof fn !== 'function')
throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn);
const ret = this.runInAsyncScope.bind(this, fn);
ObjectDefineProperties(ret, {
'length': {
enumerable: true,
value: fn.length,
},
'asyncResource': {
enumerable: true,
value: this,
}
});
return ret;
}
static bind(fn, type) {
type = type || fn.name;
return (new AsyncResource(type || 'bound-anonymous-fn')).bind(fn);
}
}
const storageList = [];