-
Notifications
You must be signed in to change notification settings - Fork 29.7k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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: #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>
- Loading branch information
Showing
3 changed files
with
90 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
'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()); | ||
}); |