@@ -105,46 +105,49 @@ export default class RedisSocket extends EventEmitter {
105105 throw new Error ( 'Socket already opened' ) ;
106106 }
107107
108- return this . #connect( 0 ) ;
108+ return this . #connect( ) ;
109109 }
110110
111- async #connect( retries : number , hadError ?: boolean ) : Promise < void > {
112- if ( retries > 0 || hadError ) {
113- this . emit ( 'reconnecting' ) ;
114- }
115-
116- try {
117- this . #isOpen = true ;
118- this . #socket = await this . #createSocket( ) ;
119- this . #writableNeedDrain = false ;
120- this . emit ( 'connect' ) ;
111+ async #connect( hadError ?: boolean ) : Promise < void > {
112+ let retries = 0 ;
113+ do {
114+ if ( retries > 0 || hadError ) {
115+ this . emit ( 'reconnecting' ) ;
116+ }
121117
122118 try {
123- await this . #initiator( ) ;
119+ this . #isOpen = true ;
120+ this . #socket = await this . #createSocket( ) ;
121+ this . #writableNeedDrain = false ;
122+ this . emit ( 'connect' ) ;
123+
124+ try {
125+ await this . #initiator( ) ;
126+ } catch ( err ) {
127+ this . #socket. destroy ( ) ;
128+ this . #socket = undefined ;
129+ throw err ;
130+ }
131+ this . #isReady = true ;
132+ this . emit ( 'ready' ) ;
124133 } catch ( err ) {
125- this . #socket. destroy ( ) ;
126- this . #socket = undefined ;
127- throw err ;
128- }
129- this . #isReady = true ;
130- this . emit ( 'ready' ) ;
131- } catch ( err ) {
132- const retryIn = this . reconnectStrategy ( retries ) ;
133- if ( retryIn instanceof Error ) {
134- this . #isOpen = false ;
134+ const retryIn = this . reconnectStrategy ( retries ) ;
135+ if ( retryIn instanceof Error ) {
136+ this . #isOpen = false ;
137+ this . emit ( 'error' , err ) ;
138+ throw new ReconnectStrategyError ( retryIn , err ) ;
139+ }
140+
135141 this . emit ( 'error' , err ) ;
136- throw new ReconnectStrategyError ( retryIn , err ) ;
142+ await promiseTimeout ( retryIn ) ;
137143 }
138-
139- this . emit ( 'error' , err ) ;
140- await promiseTimeout ( retryIn ) ;
141- return this . #connect( retries + 1 ) ;
142- }
144+ retries ++ ;
145+ } while ( ! this . #isReady) ;
143146 }
144147
145148 #createSocket( ) : Promise < net . Socket | tls . TLSSocket > {
146149 return new Promise ( ( resolve , reject ) => {
147- const { connectEvent, socket} = RedisSocket . #isTlsSocket( this . #options) ?
150+ const { connectEvent, socket } = RedisSocket . #isTlsSocket( this . #options) ?
148151 this . #createTlsSocket( ) :
149152 this . #createNetSocket( ) ;
150153
@@ -200,7 +203,7 @@ export default class RedisSocket extends EventEmitter {
200203 this . #isReady = false ;
201204 this . emit ( 'error' , err ) ;
202205
203- this . #connect( 0 , true ) . catch ( ( ) => {
206+ this . #connect( true ) . catch ( ( ) => {
204207 // the error was already emitted, silently ignore it
205208 } ) ;
206209 }
0 commit comments