diff --git a/lib/async_hooks.js b/lib/async_hooks.js index af5a37b749d94b..c4d96eb666fd93 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -223,15 +223,18 @@ class AsyncResource { return this[trigger_async_id_symbol]; } - bind(fn, thisArg = this) { + bind(fn, thisArg) { validateFunction(fn, 'fn'); - const ret = - FunctionPrototypeBind( - this.runInAsyncScope, - this, - fn, - thisArg); - ObjectDefineProperties(ret, { + const runInAsyncScope = FunctionPrototypeBind( + this.runInAsyncScope, + this, + fn); + const bound = function (...args) { + return runInAsyncScope( + thisArg !== undefined ? thisArg : this, + ...args); + }; + ObjectDefineProperties(bound, { 'length': { configurable: true, enumerable: false, @@ -245,7 +248,7 @@ class AsyncResource { writable: true, } }); - return ret; + return bound; } static bind(fn, type, thisArg) { diff --git a/test/parallel/test-asyncresource-bind.js b/test/parallel/test-asyncresource-bind.js index a9f613d9302edf..29de9bbb0f10bb 100644 --- a/test/parallel/test-asyncresource-bind.js +++ b/test/parallel/test-asyncresource-bind.js @@ -41,7 +41,7 @@ const fn3 = asyncResource.bind(common.mustCall(function() { fn3(); const fn4 = asyncResource.bind(common.mustCall(function() { - assert.strictEqual(this, asyncResource); + assert.strictEqual(this, undefined); })); fn4(); @@ -49,3 +49,8 @@ const fn5 = asyncResource.bind(common.mustCall(function() { assert.strictEqual(this, false); }), false); fn5(); + +const fn6 = asyncResource.bind(common.mustCall(function() { + assert.strictEqual(this, 'test'); +})); +fn6.call('test');