Skip to content

Commit 141977e

Browse files
committed
fix AsyncResource.bind not using 'this' from the caller by default
1 parent ef30a22 commit 141977e

File tree

2 files changed

+18
-10
lines changed

2 files changed

+18
-10
lines changed

lib/async_hooks.js

+12-9
Original file line numberDiff line numberDiff line change
@@ -223,15 +223,18 @@ class AsyncResource {
223223
return this[trigger_async_id_symbol];
224224
}
225225

226-
bind(fn, thisArg = this) {
226+
bind(fn, thisArg) {
227227
validateFunction(fn, 'fn');
228-
const ret =
229-
FunctionPrototypeBind(
230-
this.runInAsyncScope,
231-
this,
232-
fn,
233-
thisArg);
234-
ObjectDefineProperties(ret, {
228+
const runInAsyncScope = FunctionPrototypeBind(
229+
this.runInAsyncScope,
230+
this,
231+
fn);
232+
const bound = function (...args) {
233+
return runInAsyncScope(
234+
thisArg !== undefined ? thisArg : this,
235+
...args);
236+
};
237+
ObjectDefineProperties(bound, {
235238
'length': {
236239
configurable: true,
237240
enumerable: false,
@@ -245,7 +248,7 @@ class AsyncResource {
245248
writable: true,
246249
}
247250
});
248-
return ret;
251+
return bound;
249252
}
250253

251254
static bind(fn, type, thisArg) {

test/parallel/test-asyncresource-bind.js

+6-1
Original file line numberDiff line numberDiff line change
@@ -41,11 +41,16 @@ const fn3 = asyncResource.bind(common.mustCall(function() {
4141
fn3();
4242

4343
const fn4 = asyncResource.bind(common.mustCall(function() {
44-
assert.strictEqual(this, asyncResource);
44+
assert.strictEqual(this, undefined);
4545
}));
4646
fn4();
4747

4848
const fn5 = asyncResource.bind(common.mustCall(function() {
4949
assert.strictEqual(this, false);
5050
}), false);
5151
fn5();
52+
53+
const fn6 = asyncResource.bind(common.mustCall(function() {
54+
assert.strictEqual(this, 'test');
55+
}));
56+
fn6.call('test');

0 commit comments

Comments
 (0)