@@ -10,6 +10,8 @@ const {
1010 ObjectDefineProperty,
1111 ObjectGetPrototypeOf,
1212 ObjectSetPrototypeOf,
13+ Promise,
14+ PromisePrototypeThen,
1315 ReflectApply,
1416 SafeFinalizationRegistry,
1517 SafeMap,
@@ -26,6 +28,7 @@ const {
2628} = require ( 'internal/validators' ) ;
2729
2830const { triggerUncaughtException } = internalBinding ( 'errors' ) ;
31+ const { isPromise } = require ( 'internal/util/types' ) ;
2932
3033const dc_binding = internalBinding ( 'diagnostics_channel' ) ;
3134const { subscribers : subscriberCounts } = dc_binding ;
@@ -369,16 +372,20 @@ class TracingChannel {
369372
370373 const { start, end, asyncStart, asyncEnd, error } = this ;
371374
372- function reject ( err ) {
375+ function onReject ( err ) {
373376 context . error = err ;
374377 error . publish ( context ) ;
375378 asyncStart . publish ( context ) ;
376379 // TODO: Is there a way to have asyncEnd _after_ the continuation?
377380 asyncEnd . publish ( context ) ;
381+ }
382+
383+ function onRejectWithRethrow ( err ) {
384+ onReject ( err ) ;
378385 throw err ;
379386 }
380387
381- function resolve ( result ) {
388+ function onResolve ( result ) {
382389 context . result = result ;
383390 asyncStart . publish ( context ) ;
384391 // TODO: Is there a way to have asyncEnd _after_ the continuation?
@@ -396,7 +403,17 @@ class TracingChannel {
396403 context . result = result ;
397404 return result ;
398405 }
399- return result . then ( resolve , reject ) ;
406+ // isPromise() matches sub-classes, but we need to match only direct
407+ // instances of the native Promise type to safely use PromisePrototypeThen.
408+ if ( isPromise ( result ) && result . constructor === Promise ) {
409+ return PromisePrototypeThen ( result , onResolve , onRejectWithRethrow ) ;
410+ }
411+ // For non-native thenables, subscribe to the result but return the
412+ // original thenable so the consumer can continue handling it directly.
413+ // Non-native thenables don't have unhandledRejection tracking, so
414+ // swallowing the rejection here doesn't change existing behaviour.
415+ result . then ( onResolve , onReject ) ;
416+ return result ;
400417 } catch ( err ) {
401418 context . error = err ;
402419 error . publish ( context ) ;
0 commit comments