@@ -130,24 +130,14 @@ export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptio
130
130
await new Promise < void > ( ( resolve , reject ) => {
131
131
const start = Date . now ( )
132
132
133
- // Attempt to end the socket. If it takes longer to close than the
134
- // timeout, destroy it manually.
135
- const timeout = setTimeout ( ( ) => {
136
- if ( socket . destroyed ) {
137
- log ( '%s is already destroyed' , lOptsStr )
138
- resolve ( )
139
- } else {
140
- log ( '%s socket close timeout after %dms, destroying it manually' , lOptsStr , Date . now ( ) - start )
141
-
142
- // will trigger 'error' and 'close' events that resolves promise
143
- socket . destroy ( new CodeError ( 'Socket close timeout' , 'ERR_SOCKET_CLOSE_TIMEOUT' ) )
144
- }
145
- } , closeTimeout ) . unref ( )
133
+ let timeout : NodeJS . Timeout | undefined
146
134
147
135
socket . once ( 'close' , ( ) => {
148
136
log ( '%s socket closed' , lOptsStr )
149
137
// socket completely closed
150
- clearTimeout ( timeout )
138
+ if ( timeout !== undefined ) {
139
+ clearTimeout ( timeout )
140
+ }
151
141
resolve ( )
152
142
} )
153
143
socket . once ( 'error' , ( err : Error ) => {
@@ -159,7 +149,9 @@ export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptio
159
149
}
160
150
161
151
if ( socket . destroyed ) {
162
- clearTimeout ( timeout )
152
+ if ( timeout !== undefined ) {
153
+ clearTimeout ( timeout )
154
+ }
163
155
}
164
156
165
157
reject ( err )
@@ -172,6 +164,19 @@ export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptio
172
164
socket . end ( )
173
165
174
166
if ( socket . writableLength > 0 ) {
167
+ // Attempt to end the socket. If it takes longer to close than the
168
+ // timeout, destroy it manually.
169
+ timeout = setTimeout ( ( ) => {
170
+ if ( socket . destroyed ) {
171
+ log ( '%s is already destroyed' , lOptsStr )
172
+ resolve ( )
173
+ } else {
174
+ log ( '%s socket close timeout after %dms, destroying it manually' , lOptsStr , Date . now ( ) - start )
175
+
176
+ // will trigger 'error' and 'close' events that resolves promise
177
+ socket . destroy ( new CodeError ( 'Socket close timeout' , 'ERR_SOCKET_CLOSE_TIMEOUT' ) )
178
+ }
179
+ } , closeTimeout ) . unref ( )
175
180
// there are outgoing bytes waiting to be sent
176
181
socket . once ( 'drain' , ( ) => {
177
182
log ( '%s socket drained' , lOptsStr )
@@ -180,7 +185,7 @@ export const toMultiaddrConnection = (socket: Socket, options: ToConnectionOptio
180
185
socket . destroy ( )
181
186
} )
182
187
} else {
183
- // nothing to send, destroy immediately
188
+ // nothing to send, destroy immediately, no need the timeout
184
189
socket . destroy ( )
185
190
}
186
191
} )
0 commit comments