@@ -778,8 +778,13 @@ class AspectWatchProtocol {
778
778
await new Promise ( ( resolve , reject ) => {
779
779
// Initial connection + success vs failure
780
780
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
+ }
783
788
} )
784
789
785
790
await this . _receive ( 'NEGOTIATE' )
@@ -844,14 +849,33 @@ class AspectWatchProtocol {
844
849
const dataBufs = [ ]
845
850
const connection = this . connection
846
851
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 ) {
848
871
dataBufs . push ( data )
849
872
850
873
if ( data . at ( data . byteLength - 1 ) !== '\n' . charCodeAt ( 0 ) ) {
851
874
return
852
875
}
853
876
854
- connection . off ( 'data' , dataReceived )
877
+ // Removal all temporary event handlers before resolving the promise
878
+ removeHandlers ( )
855
879
856
880
try {
857
881
const msg = JSON . parse (
@@ -869,7 +893,7 @@ class AspectWatchProtocol {
869
893
} catch ( e ) {
870
894
reject ( e )
871
895
}
872
- } )
896
+ }
873
897
} )
874
898
}
875
899
0 commit comments