Skip to content

Commit 029b68f

Browse files
committed
async_hooks: fix Promises with later enabled hooks
Assign a `PromiseWrap` instance to Promises that do not have one yet when the PromiseHook is being called. Fixes: #13237
1 parent 7f444ff commit 029b68f

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

src/async-wrap.cc

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -293,13 +293,14 @@ static void PromiseHook(PromiseHookType type, Local<Promise> promise,
293293
Local<Value> parent, void* arg) {
294294
Local<Context> context = promise->CreationContext();
295295
Environment* env = Environment::GetCurrent(context);
296-
if (type == PromiseHookType::kInit) {
297-
PromiseWrap* wrap = new PromiseWrap(env, promise);
296+
PromiseWrap* wrap = Unwrap<PromiseWrap>(promise);
297+
if (type == PromiseHookType::kInit ||
298+
wrap == nullptr) {
299+
wrap = new PromiseWrap(env, promise);
298300
wrap->MakeWeak(wrap);
299301
} else if (type == PromiseHookType::kResolve) {
300302
// TODO(matthewloring): need to expose this through the async hooks api.
301303
}
302-
PromiseWrap* wrap = Unwrap<PromiseWrap>(promise);
303304
CHECK_NE(wrap, nullptr);
304305
if (type == PromiseHookType::kBefore) {
305306
PreCallbackExecution(wrap, false);
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
'use strict';
2+
3+
// Regression test for https://github.com/nodejs/node/issues/13237
4+
5+
const common = require('../common');
6+
const assert = require('assert');
7+
8+
const async_hooks = require('async_hooks');
9+
10+
const seenEvents = [];
11+
12+
const p = new Promise((resolve) => resolve(1));
13+
p.then(() => seenEvents.push('then'));
14+
15+
const hooks = async_hooks.createHook({
16+
before: common.mustCall((id) => {
17+
assert.ok(id > 1);
18+
seenEvents.push('before');
19+
}),
20+
21+
after: common.mustCall((id) => {
22+
assert.ok(id > 1);
23+
seenEvents.push('after');
24+
hooks.disable();
25+
})
26+
}).enable();
27+
28+
setImmediate(() => {
29+
assert.deepStrictEqual(seenEvents, ['before', 'then', 'after']);
30+
});

0 commit comments

Comments
 (0)