@@ -44,6 +44,7 @@ const {
44
44
const net = require ( 'net' ) ;
45
45
const url = require ( 'url' ) ;
46
46
const assert = require ( 'internal/assert' ) ;
47
+ const { once } = require ( 'internal/util' ) ;
47
48
const {
48
49
_checkIsHttpToken : checkIsHttpToken ,
49
50
debug,
@@ -240,8 +241,6 @@ function ClientRequest(input, options, cb) {
240
241
this . host = host ;
241
242
this . protocol = protocol ;
242
243
243
- let called = false ;
244
-
245
244
if ( this . agent ) {
246
245
// If there is an agent we should default to Connection:keep-alive,
247
246
// but only if the Agent will actually reuse the connection!
@@ -305,18 +304,6 @@ function ClientRequest(input, options, cb) {
305
304
options . headers ) ;
306
305
}
307
306
308
- const oncreate = ( err , socket ) => {
309
- if ( called )
310
- return ;
311
- called = true ;
312
- if ( err ) {
313
- process . nextTick ( ( ) => this . emit ( 'error' , err ) ) ;
314
- return ;
315
- }
316
- this . onSocket ( socket ) ;
317
- this . _deferToConnect ( null , null , ( ) => this . _flush ( ) ) ;
318
- } ;
319
-
320
307
// initiate connection
321
308
if ( this . agent ) {
322
309
this . agent . addRequest ( this , options ) ;
@@ -325,20 +312,27 @@ function ClientRequest(input, options, cb) {
325
312
this . _last = true ;
326
313
this . shouldKeepAlive = false ;
327
314
if ( typeof options . createConnection === 'function' ) {
328
- const newSocket = options . createConnection ( options , oncreate ) ;
329
- if ( newSocket && ! called ) {
330
- called = true ;
331
- this . onSocket ( newSocket ) ;
332
- } else {
333
- return ;
315
+ const oncreate = once ( ( err , socket ) => {
316
+ if ( err ) {
317
+ process . nextTick ( ( ) => this . emit ( 'error' , err ) ) ;
318
+ } else {
319
+ this . onSocket ( socket ) ;
320
+ }
321
+ } ) ;
322
+
323
+ try {
324
+ const newSocket = options . createConnection ( options , oncreate ) ;
325
+ if ( newSocket ) {
326
+ oncreate ( null , newSocket ) ;
327
+ }
328
+ } catch ( err ) {
329
+ oncreate ( err ) ;
334
330
}
335
331
} else {
336
332
debug ( 'CLIENT use net.createConnection' , options ) ;
337
333
this . onSocket ( net . createConnection ( options ) ) ;
338
334
}
339
335
}
340
-
341
- this . _deferToConnect ( null , null , ( ) => this . _flush ( ) ) ;
342
336
}
343
337
ObjectSetPrototypeOf ( ClientRequest . prototype , OutgoingMessage . prototype ) ;
344
338
ObjectSetPrototypeOf ( ClientRequest , OutgoingMessage ) ;
@@ -843,6 +837,7 @@ function onSocketNT(req, socket, err) {
843
837
_destroy ( req , null , err ) ;
844
838
} else {
845
839
tickOnSocket ( req , socket ) ;
840
+ req . _flush ( ) ;
846
841
}
847
842
}
848
843
0 commit comments