@@ -105,46 +105,49 @@ export default class RedisSocket extends EventEmitter {
105
105
throw new Error ( 'Socket already opened' ) ;
106
106
}
107
107
108
- return this . #connect( 0 ) ;
108
+ return this . #connect( ) ;
109
109
}
110
110
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
+ }
121
117
122
118
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' ) ;
124
133
} 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
+
135
141
this . emit ( 'error' , err ) ;
136
- throw new ReconnectStrategyError ( retryIn , err ) ;
142
+ await promiseTimeout ( retryIn ) ;
137
143
}
138
-
139
- this . emit ( 'error' , err ) ;
140
- await promiseTimeout ( retryIn ) ;
141
- return this . #connect( retries + 1 ) ;
142
- }
144
+ retries ++ ;
145
+ } while ( ! this . #isReady) ;
143
146
}
144
147
145
148
#createSocket( ) : Promise < net . Socket | tls . TLSSocket > {
146
149
return new Promise ( ( resolve , reject ) => {
147
- const { connectEvent, socket} = RedisSocket . #isTlsSocket( this . #options) ?
150
+ const { connectEvent, socket } = RedisSocket . #isTlsSocket( this . #options) ?
148
151
this . #createTlsSocket( ) :
149
152
this . #createNetSocket( ) ;
150
153
@@ -200,7 +203,7 @@ export default class RedisSocket extends EventEmitter {
200
203
this . #isReady = false ;
201
204
this . emit ( 'error' , err ) ;
202
205
203
- this . #connect( 0 , true ) . catch ( ( ) => {
206
+ this . #connect( true ) . catch ( ( ) => {
204
207
// the error was already emitted, silently ignore it
205
208
} ) ;
206
209
}
0 commit comments