forked from nodejs/node-addon-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcallbackscope.js
49 lines (44 loc) · 1.21 KB
/
callbackscope.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
'use strict';
const assert = require('assert');
// we only check async hooks on 8.x an higher were
// they are closer to working properly
const nodeVersion = process.versions.node.split('.')[0];
let asyncHooks;
function checkAsyncHooks () {
if (nodeVersion >= 8) {
if (asyncHooks === undefined) {
asyncHooks = require('async_hooks');
}
return true;
}
return false;
}
module.exports = require('./common').runTest(test);
function test (binding) {
if (!checkAsyncHooks()) { return; }
let id;
let insideHook = false;
const hook = asyncHooks.createHook({
init (asyncId, type, triggerAsyncId, resource) {
if (id === undefined && (type === 'callback_scope_test' || type === 'existing_callback_scope_test')) {
id = asyncId;
}
},
before (asyncId) {
if (asyncId === id) { insideHook = true; }
},
after (asyncId) {
if (asyncId === id) { insideHook = false; }
}
}).enable();
return new Promise(resolve => {
binding.callbackscope.runInCallbackScope(function () {
assert(insideHook);
binding.callbackscope.runInPreExistingCbScope(function () {
assert(insideHook);
hook.disable();
resolve();
});
});
});
}