From 6ed05c9dc482b9b9400da9a590a7cd147f4acbd4 Mon Sep 17 00:00:00 2001 From: Sajal Khandelwal Date: Sun, 7 Feb 2021 11:33:33 -0500 Subject: [PATCH] draft --- lib/internal/async_hooks.js | 2 ++ lib/internal/process/promises.js | 38 +++++++++++++++++++++++++------- 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/lib/internal/async_hooks.js b/lib/internal/async_hooks.js index f3014318071d9f..4c02a32c4c3d6f 100644 --- a/lib/internal/async_hooks.js +++ b/lib/internal/async_hooks.js @@ -573,6 +573,8 @@ module.exports = { emitBefore: emitBeforeScript, emitAfter: emitAfterScript, emitDestroy: emitDestroyScript, + pushAsyncContext, + popAsyncContext, registerDestroyHook, useDomainTrampoline, nativeHooks: { diff --git a/lib/internal/process/promises.js b/lib/internal/process/promises.js index 023f7df0360d02..b33bdca5226a45 100644 --- a/lib/internal/process/promises.js +++ b/lib/internal/process/promises.js @@ -24,6 +24,14 @@ const { triggerUncaughtException } = internalBinding('errors'); +const { + pushAsyncContext, + popAsyncContext, +} = require('internal/async_hooks'); +const async_hooks = require('async_hooks'); + +const { emit } = require('process'); + // *Must* match Environment::TickInfo::Fields in src/env.h. const kHasRejectionToWarn = 1; @@ -116,12 +124,31 @@ function resolveError(type, promise, reason) { } function unhandledRejection(promise, reason) { + const asyncId = async_hooks.executionAsyncId(); + const triggerAsyncId = async_hooks.triggerAsyncId(); + const resource = promise; + + const emit = (reason, promise, promiseInfo) => { + try { + pushAsyncContext(asyncId, triggerAsyncId, resource); + if (promiseInfo.domain) { + return promiseInfo.domain.emit('error', reason); + } + return process.emit('unhandledRejection', reason, promise); + } + finally { + popAsyncContext(asyncId); + } + }; + maybeUnhandledPromises.set(promise, { reason, uid: ++lastPromiseId, warned: false, - domain: process.domain + domain: process.domain, + emit }); + console.log("in unhandledRejection", require('async_hooks').executionAsyncId()); // This causes the promise to be referenced at least for one tick. ArrayPrototypePush(pendingUnhandledRejections, promise); setHasRejectionToWarn(true); @@ -194,13 +221,8 @@ function processPromiseRejections() { continue; } promiseInfo.warned = true; - const { reason, uid } = promiseInfo; - function emit(reason, promise, promiseInfo) { - if (promiseInfo.domain) { - return promiseInfo.domain.emit('error', reason); - } - return process.emit('unhandledRejection', reason, promise); - } + const { reason, uid, emit } = promiseInfo; + switch (unhandledRejectionsMode) { case kStrictUnhandledRejections: { const err = reason instanceof Error ?