@@ -781,8 +781,13 @@ class AspectWatchProtocol {
781
781
await new Promise ( ( resolve , reject ) => {
782
782
// Initial connection + success vs failure
783
783
this . connection . once ( 'error' , reject )
784
- this . connection . once ( 'connect' , resolve )
785
- this . connection . connect ( { path : this . socketFile } )
784
+ try {
785
+ this . connection . connect ( { path : this . socketFile } , resolve )
786
+ } catch ( err ) {
787
+ reject ( err )
788
+ } finally {
789
+ this . connection . off ( 'error' , reject )
790
+ }
786
791
} )
787
792
788
793
await this . _receive ( 'NEGOTIATE' )
@@ -847,14 +852,33 @@ class AspectWatchProtocol {
847
852
const dataBufs = [ ]
848
853
const connection = this . connection
849
854
850
- connection . on ( 'data' , function dataReceived ( data ) {
855
+ connection . once ( 'error' , onError )
856
+ connection . once ( 'close' , onError )
857
+ connection . on ( 'data' , dataReceived )
858
+
859
+ // Destructor removing all temporary event handlers.
860
+ function removeHandlers ( ) {
861
+ connection . off ( 'error' , onError )
862
+ connection . off ( 'close' , onError )
863
+ connection . off ( 'data' , dataReceived )
864
+ }
865
+
866
+ // Error event handler
867
+ function onError ( err ) {
868
+ removeHandlers ( )
869
+ reject ( err )
870
+ }
871
+
872
+ // Data event handler to receive data and determine when to resolve the promise.
873
+ function dataReceived ( data ) {
851
874
dataBufs . push ( data )
852
875
853
876
if ( data . at ( data . byteLength - 1 ) !== '\n' . charCodeAt ( 0 ) ) {
854
877
return
855
878
}
856
879
857
- connection . off ( 'data' , dataReceived )
880
+ // Removal all temporary event handlers before resolving the promise
881
+ removeHandlers ( )
858
882
859
883
try {
860
884
const msg = JSON . parse (
@@ -872,7 +896,7 @@ class AspectWatchProtocol {
872
896
} catch ( e ) {
873
897
reject ( e )
874
898
}
875
- } )
899
+ }
876
900
} )
877
901
}
878
902
0 commit comments