@@ -778,8 +778,13 @@ class AspectWatchProtocol {
778778 await new Promise ( ( resolve , reject ) => {
779779 // Initial connection + success vs failure
780780 this . connection . once ( 'error' , reject )
781- this . connection . once ( 'connect' , resolve )
782- this . connection . connect ( { path : this . socketFile } )
781+ try {
782+ this . connection . connect ( { path : this . socketFile } , resolve )
783+ } catch ( err ) {
784+ reject ( err )
785+ } finally {
786+ this . connection . off ( 'error' , reject )
787+ }
783788 } )
784789
785790 await this . _receive ( 'NEGOTIATE' )
@@ -844,14 +849,33 @@ class AspectWatchProtocol {
844849 const dataBufs = [ ]
845850 const connection = this . connection
846851
847- connection . on ( 'data' , function dataReceived ( data ) {
852+ connection . once ( 'error' , onError )
853+ connection . once ( 'close' , onError )
854+ connection . on ( 'data' , dataReceived )
855+
856+ // Destructor removing all temporary event handlers.
857+ function removeHandlers ( ) {
858+ connection . off ( 'error' , onError )
859+ connection . off ( 'close' , onError )
860+ connection . off ( 'data' , dataReceived )
861+ }
862+
863+ // Error event handler
864+ function onError ( err ) {
865+ removeHandlers ( )
866+ reject ( err )
867+ }
868+
869+ // Data event handler to receive data and determine when to resolve the promise.
870+ function dataReceived ( data ) {
848871 dataBufs . push ( data )
849872
850873 if ( data . at ( data . byteLength - 1 ) !== '\n' . charCodeAt ( 0 ) ) {
851874 return
852875 }
853876
854- connection . off ( 'data' , dataReceived )
877+ // Removal all temporary event handlers before resolving the promise
878+ removeHandlers ( )
855879
856880 try {
857881 const msg = JSON . parse (
@@ -869,7 +893,7 @@ class AspectWatchProtocol {
869893 } catch ( e ) {
870894 reject ( e )
871895 }
872- } )
896+ }
873897 } )
874898 }
875899
0 commit comments