@@ -504,6 +504,12 @@ export function createSessionOperationQueue(): SessionOperationQueue {
504504 } ) ;
505505 } ;
506506
507+ // `observed === activeResult` is the adoption of a thenable returned from
508+ // the op. That `.then` runs after AsyncLocalStorage.run returns.
509+ const isSelfWait = ( during : number , observed : object ) : boolean =>
510+ activeId === during &&
511+ ( observed === activeResult || ( inThisOp ( ) && bodyStillRunning ( ) ) ) ;
512+
507513 const enqueue = ( op : ( ) => Promise < void > ) : Promise < void > => {
508514 // `tail.then(op, op)` — a failed op must not wedge the chain. The
509515 // returned promise is not that tail: a self-wait rejection has to
@@ -515,9 +521,8 @@ export function createSessionOperationQueue(): SessionOperationQueue {
515521 tail = scheduled ;
516522 if ( ! inThisOp ( ) ) return scheduled ;
517523 const enqueuedDuring = activeId ;
518- return observeUnlessSelfWait (
519- scheduled ,
520- ( ) => inThisOp ( ) && activeId === enqueuedDuring && bodyStillRunning ( ) ,
524+ return observeUnlessSelfWait ( scheduled , ( observed ) =>
525+ isSelfWait ( enqueuedDuring , observed ) ,
521526 ) ;
522527 } ;
523528
@@ -528,9 +533,8 @@ export function createSessionOperationQueue(): SessionOperationQueue {
528533 // deadlocks the same way as awaiting enqueue.
529534 if ( ! inThisOp ( ) ) return drained ;
530535 const awaitedDuring = activeId ;
531- return observeUnlessSelfWait (
532- drained ,
533- ( ) => inThisOp ( ) && activeId === awaitedDuring && bodyStillRunning ( ) ,
536+ return observeUnlessSelfWait ( drained , ( observed ) =>
537+ isSelfWait ( awaitedDuring , observed ) ,
534538 ) ;
535539 } ;
536540
@@ -545,7 +549,7 @@ export function createSessionOperationQueue(): SessionOperationQueue {
545549 */
546550function observeUnlessSelfWait (
547551 forward : Promise < void > ,
548- stillRunning : ( ) => boolean ,
552+ stillRunning : ( observed : object ) => boolean ,
549553) : Promise < void > {
550554 let reported : SessionOperationSelfWaitError | undefined ;
551555 let guarded = false ;
@@ -583,7 +587,7 @@ function observeUnlessSelfWait(
583587 ) : Promise < undefined > ;
584588 } = {
585589 then ( onFulfilled , onRejected ) {
586- if ( stillRunning ( ) ) {
590+ if ( stillRunning ( thenable ) ) {
587591 guardUnobserved ( ) ;
588592 return reject ( ) . then ( onFulfilled , onRejected ) ;
589593 }
0 commit comments