Skip to content

Commit 979894c

Browse files
committed
async_hooks: use parent promise as triggerId in init hook
async_hooks init callback will be triggered when promise newly created, in previous version, the parent promise which pass from chrome V8 PromiseHook is ignored, so we can't tell the promise is a pure new promise or a chained promise. In this commit, we use the parent promise's id as triggerId to trigger the init callback. Fixes: nodejs#13302
1 parent e824c75 commit 979894c

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/async-wrap.cc

+17
Original file line numberDiff line numberDiff line change
@@ -296,6 +296,23 @@ static void PromiseHook(PromiseHookType type, Local<Promise> promise,
296296
PromiseWrap* wrap = Unwrap<PromiseWrap>(promise);
297297
if (type == PromiseHookType::kInit || wrap == nullptr) {
298298
bool silent = type != PromiseHookType::kInit;
299+
// set parent promise's async Id as this promise's triggerId
300+
if (parent->IsPromise()) {
301+
// parent promise exists, current promise
302+
// is a chained promise, so we set parent promise's id as
303+
// current promise's triggerId
304+
Local<Promise> parent_promise = parent.As<Promise>();
305+
auto parent_wrap = Unwrap<PromiseWrap>(parent_promise);
306+
307+
if (parent_wrap == nullptr) {
308+
// create a new PromiseWrap for parent promise with silent parameter
309+
parent_wrap = new PromiseWrap(env, parent_promise, true);
310+
parent_wrap->MakeWeak(parent_wrap);
311+
}
312+
// get id from parentWrap
313+
double trigger_id = parent_wrap->get_id();
314+
env->set_init_trigger_id(trigger_id);
315+
}
299316
wrap = new PromiseWrap(env, promise, silent);
300317
wrap->MakeWeak(wrap);
301318
} else if (type == PromiseHookType::kResolve) {

test/async-hooks/test-promise.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ function onexit() {
4646
const a1 = as[1];
4747
assert.strictEqual(a1.type, 'PROMISE', 'promise request');
4848
assert.strictEqual(typeof a1.uid, 'number', 'uid is a number');
49-
assert.strictEqual(a1.triggerId, 1, 'parent uid 1');
49+
assert.strictEqual(a1.triggerId, 2, 'parent triggerId 2');
5050
// We expect a destroy hook as well but we cannot guarentee predictable gc.
5151
checkInvocations(a1, { init: 1, before: 1, after: 1 }, 'when process exits');
5252
}

0 commit comments

Comments
 (0)