nodejs/test/parallel/test-asyncresource-bind.js
James M Snell 324a6c235a
async_hooks: add thisArg to AsyncResource.bind
Semver-major

Support setting the `thisArg` for AsyncResource.bind and
AsyncResource.prototype.bind. If `thisArg` is not set,
then `this` will be set to the `AsyncResource` instance.

Fixes: https://github.com/nodejs/node/issues/36051
Signed-off-by: James M Snell <jasnell@gmail.com>

PR-URL: https://github.com/nodejs/node/pull/36782
Reviewed-By: Juan José Arboleda <soyjuanarbol@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
2021-01-09 11:22:35 -08:00

52 lines
1.2 KiB
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
const { AsyncResource, executionAsyncId } = require('async_hooks');
const fn = common.mustCall(AsyncResource.bind(() => {
return executionAsyncId();
}));
setImmediate(() => {
const asyncId = executionAsyncId();
assert.notStrictEqual(asyncId, fn());
});
const asyncResource = new AsyncResource('test');
[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());
assert.notStrictEqual(asyncId, fn2());
});
const foo = {};
const fn3 = asyncResource.bind(common.mustCall(function() {
assert.strictEqual(this, foo);
}), foo);
fn3();
const fn4 = asyncResource.bind(common.mustCall(function() {
assert.strictEqual(this, asyncResource);
}));
fn4();
const fn5 = asyncResource.bind(common.mustCall(function() {
assert.strictEqual(this, false);
}), false);
fn5();