async_hooks: use parent promise as triggerId in init hook by JiaLiPassion · Pull Request #13367 · nodejs/node (original) (raw)
@AndreasMadsen , about the sample code you provided,
Consider the following code:
const p0 = new Promise((resolve) => resolve(1)); const p1 = p0.then(function () { // async_hooks.currentId() === asyncId(p1) p2 = p1.then(function () { // trigger_id = asyncId(p1)
}); return 2; });
I make a test with this PR compiled node.
const async_hooks = require('async_hooks');
function init(id, provider, parentId, parentHandle) { process._rawDebug('init: ', id, 'triggerId: ', parentId, 'currentId', async_hooks.currentId()); }
function before(id) { process._rawDebug('before', id, async_hooks.currentId()); } function after(id) { process._rawDebug('after', id, async_hooks.currentId()); } function destroy(id) { process._rawDebug('destroy', id); }
async_hooks.createHook({init, before, after, destroy}).enable(); debugger; const p = new Promise ( resolve => { process._rawDebug('execute p'); resolve(1);} ); const p1 = p.then(val => { process._rawDebug('p1 then', val); const p2 = p1.then((val1) => { process._rawDebug('p2 then', val1); }); return 2; });
the output is
init: 2 triggerId: 1 currentId 1
execute p
init: 3 triggerId: 2 currentId 1
before 3 1
p1 then 1
init: 4 triggerId: 3 currentId 1
after 3 1
before 4 1
p2 then 2
after 4 1
p is promise without parent, so triggerId === currentId
p1 is promise , and p1's parent is p, so the triggerId is 2
p2 is promise , and p2's parent is p1, so the triggerId is 3,
I think this a correct result.
And I tried another case
setTimeout(() => { const p = new Promise(resolve => { process._rawDebug('execute p'); resolve(1); }); const p1 = p.then(val => { process._rawDebug('p1 then', val); const p2 = p1.then((val1) => { process._rawDebug('p2 then', val1); }); return 2; });
}, 100);
the output is
init: 2 type: Timeout triggerId: 1 currentId 1
init: 3 type: TIMERWRAP triggerId: 1 currentId 1
before 3 3
before 2 2
init: 4 type: PROMISE triggerId: 2 currentId 2
execute p
init: 5 type: PROMISE triggerId: 4 currentId 2
after 2 2
after 3 3
before 5 0
p1 then 1
init: 6 type: PROMISE triggerId: 5 currentId 0
after 5 0
before 6 0
p2 then 2
after 6 0
destroy 2
I think the result is also ok, but I don't quite understand the why currentId
will become 0
.
Please review. Thank you very much!