Skip to content

Commit

Permalink
fixup! async_hooks: add AsyncResource.bind utility
Browse files Browse the repository at this point in the history
  • Loading branch information
jasnell committed Aug 4, 2020
1 parent 6c6bdf8 commit 1432c48
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 2 deletions.
6 changes: 6 additions & 0 deletions doc/api/async_hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -740,6 +740,9 @@ added: REPLACEME

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
Expand All @@ -749,6 +752,9 @@ added: REPLACEME

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
Expand Down
17 changes: 16 additions & 1 deletion lib/async_hooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@

const {
NumberIsSafeInteger,
ObjectDefineProperties,
ReflectApply,
Symbol,
} = primordials;

const {
ERR_ASYNC_CALLBACK,
ERR_ASYNC_TYPE,
ERR_INVALID_ARG_TYPE,
ERR_INVALID_ASYNC_ID
} = require('internal/errors').codes;
const { validateString } = require('internal/validators');
Expand Down Expand Up @@ -213,7 +215,20 @@ class AsyncResource {
}

bind(fn) {
return this.runInAsyncScope.bind(this, 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) {
Expand Down
11 changes: 10 additions & 1 deletion test/parallel/test-asyncresource-bind.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,19 @@ setImmediate(() => {

const asyncResource = new AsyncResource('test');

const fn2 = asyncResource.bind(() => {
[1, false, '', {}, []].forEach((i) => {
assert.throws(() => asyncResource.bind(i), {
code: 'ERR_INVALID_ARG_TYPE'
});
});

const fn2 = asyncResource.bind((a, b) => {
return executionAsyncId();
});

assert.strictEqual(fn2.asyncResource, asyncResource);
assert.strictEqual(fn2.length, 2);

setImmediate(() => {
const asyncId = executionAsyncId();
assert.strictEqual(asyncResource.asyncId(), fn2());
Expand Down

0 comments on commit 1432c48

Please sign in to comment.