Skip to content

Commit 1432c48

Browse files
committed
fixup! async_hooks: add AsyncResource.bind utility
1 parent 6c6bdf8 commit 1432c48

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

doc/api/async_hooks.md

+6
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,9 @@ added: REPLACEME
740740

741741
Binds the given function to the current execution context.
742742

743+
The returned function will have an `asyncResource` property referencing
744+
the `AsyncResource` to which the function is bound.
745+
743746
#### `asyncResource.bind(fn)`
744747
<!-- YAML
745748
added: REPLACEME
@@ -749,6 +752,9 @@ added: REPLACEME
749752

750753
Binds the given function to execute to this `AsyncResource`'s scope.
751754

755+
The returned function will have an `asyncResource` property referencing
756+
the `AsyncResource` to which the function is bound.
757+
752758
#### `asyncResource.runInAsyncScope(fn[, thisArg, ...args])`
753759
<!-- YAML
754760
added: v9.6.0

lib/async_hooks.js

+16-1
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,15 @@
22

33
const {
44
NumberIsSafeInteger,
5+
ObjectDefineProperties,
56
ReflectApply,
67
Symbol,
78
} = primordials;
89

910
const {
1011
ERR_ASYNC_CALLBACK,
1112
ERR_ASYNC_TYPE,
13+
ERR_INVALID_ARG_TYPE,
1214
ERR_INVALID_ASYNC_ID
1315
} = require('internal/errors').codes;
1416
const { validateString } = require('internal/validators');
@@ -213,7 +215,20 @@ class AsyncResource {
213215
}
214216

215217
bind(fn) {
216-
return this.runInAsyncScope.bind(this, fn);
218+
if (typeof fn !== 'function')
219+
throw new ERR_INVALID_ARG_TYPE('fn', 'Function', fn);
220+
const ret = this.runInAsyncScope.bind(this, fn);
221+
ObjectDefineProperties(ret, {
222+
'length': {
223+
enumerable: true,
224+
value: fn.length,
225+
},
226+
'asyncResource': {
227+
enumerable: true,
228+
value: this,
229+
}
230+
});
231+
return ret;
217232
}
218233

219234
static bind(fn, type) {

test/parallel/test-asyncresource-bind.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,19 @@ setImmediate(() => {
1515

1616
const asyncResource = new AsyncResource('test');
1717

18-
const fn2 = asyncResource.bind(() => {
18+
[1, false, '', {}, []].forEach((i) => {
19+
assert.throws(() => asyncResource.bind(i), {
20+
code: 'ERR_INVALID_ARG_TYPE'
21+
});
22+
});
23+
24+
const fn2 = asyncResource.bind((a, b) => {
1925
return executionAsyncId();
2026
});
2127

28+
assert.strictEqual(fn2.asyncResource, asyncResource);
29+
assert.strictEqual(fn2.length, 2);
30+
2231
setImmediate(() => {
2332
const asyncId = executionAsyncId();
2433
assert.strictEqual(asyncResource.asyncId(), fn2());

0 commit comments

Comments
 (0)