node/test/parallel/test-asyncresource-bind.js
James M Snell 74df7496ff async_hooks: add AsyncResource.bind utility
Creates an internal AsyncResource and binds a function to it,
ensuring that the function is invoked within execution context
in which bind was called.

PR-URL: https://github.com/nodejs/node/pull/34574
Reviewed-By: Stephen Belanger <admin@stephenbelanger.com>
Reviewed-By: Gus Caplan <me@gus.host>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Andrey Pechkurov <apechkurov@gmail.com>
Reviewed-By: Gerhard Stöbich <deb2001-github@yahoo.de>
2020-08-03 18:40:16 -07:00

36 lines
854 B
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());
});