@@ -650,7 +650,7 @@ function callFinal(stream, state) {
650650 } else {
651651 state . prefinished = true ;
652652 stream . emit ( 'prefinish' ) ;
653- finishMaybe ( stream , state ) ;
653+ finishMaybe ( stream , state , false ) ;
654654 }
655655 } ) ;
656656}
@@ -667,30 +667,38 @@ function prefinish(stream, state) {
667667 }
668668}
669669
670- function finishMaybe ( stream , state ) {
670+ function finishMaybe ( stream , state , sync ) {
671671 const need = needFinish ( state ) ;
672672 if ( need ) {
673673 prefinish ( stream , state ) ;
674674 if ( state . pendingcb === 0 ) {
675- state . finished = true ;
676- stream . emit ( 'finish' ) ;
677-
678- if ( state . autoDestroy ) {
679- // In case of duplex streams we need a way to detect
680- // if the readable side is ready for autoDestroy as well
681- const rState = stream . _readableState ;
682- if ( ! rState || ( rState . autoDestroy && rState . endEmitted ) ) {
683- stream . destroy ( ) ;
684- }
675+ if ( sync ) {
676+ process . nextTick ( finishWritable , stream , state ) ;
677+ } else {
678+ finishWritable ( stream , state ) ;
685679 }
686680 }
687681 }
688682 return need ;
689683}
690684
685+ function finishWritable ( stream , state ) {
686+ state . finished = true ;
687+ stream . emit ( 'finish' ) ;
688+
689+ if ( state . autoDestroy ) {
690+ // In case of duplex streams we need a way to detect
691+ // if the readable side is ready for autoDestroy as well
692+ const rState = stream . _readableState ;
693+ if ( ! rState || ( rState . autoDestroy && rState . endEmitted ) ) {
694+ stream . destroy ( ) ;
695+ }
696+ }
697+ }
698+
691699function endWritable ( stream , state , cb ) {
692700 state . ending = true ;
693- process . nextTick ( finishMaybe , stream , state ) ;
701+ finishMaybe ( stream , state , true ) ;
694702 if ( cb ) {
695703 if ( state . finished )
696704 process . nextTick ( cb ) ;
0 commit comments