@@ -36,6 +36,7 @@ const {
3636const net = require ( 'net' ) ;
3737const url = require ( 'url' ) ;
3838const assert = require ( 'internal/assert' ) ;
39+ const { once } = require ( 'internal/util' ) ;
3940const {
4041 _checkIsHttpToken : checkIsHttpToken ,
4142 debug,
@@ -236,8 +237,6 @@ function ClientRequest(input, options, cb) {
236237 this . host = host ;
237238 this . protocol = protocol ;
238239
239- let called = false ;
240-
241240 if ( this . agent ) {
242241 // If there is an agent we should default to Connection:keep-alive,
243242 // but only if the Agent will actually reuse the connection!
@@ -301,18 +300,6 @@ function ClientRequest(input, options, cb) {
301300 options . headers ) ;
302301 }
303302
304- const oncreate = ( err , socket ) => {
305- if ( called )
306- return ;
307- called = true ;
308- if ( err ) {
309- process . nextTick ( ( ) => this . emit ( 'error' , err ) ) ;
310- return ;
311- }
312- this . onSocket ( socket ) ;
313- this . _deferToConnect ( null , null , ( ) => this . _flush ( ) ) ;
314- } ;
315-
316303 // initiate connection
317304 if ( this . agent ) {
318305 this . agent . addRequest ( this , options ) ;
@@ -321,20 +308,27 @@ function ClientRequest(input, options, cb) {
321308 this . _last = true ;
322309 this . shouldKeepAlive = false ;
323310 if ( typeof options . createConnection === 'function' ) {
324- const newSocket = options . createConnection ( options , oncreate ) ;
325- if ( newSocket && ! called ) {
326- called = true ;
327- this . onSocket ( newSocket ) ;
328- } else {
329- return ;
311+ const oncreate = once ( ( err , socket ) => {
312+ if ( err ) {
313+ process . nextTick ( ( ) => this . emit ( 'error' , err ) ) ;
314+ } else {
315+ this . onSocket ( socket ) ;
316+ }
317+ } ) ;
318+
319+ try {
320+ const newSocket = options . createConnection ( options , oncreate ) ;
321+ if ( newSocket ) {
322+ oncreate ( null , newSocket ) ;
323+ }
324+ } catch ( err ) {
325+ oncreate ( err ) ;
330326 }
331327 } else {
332328 debug ( 'CLIENT use net.createConnection' , options ) ;
333329 this . onSocket ( net . createConnection ( options ) ) ;
334330 }
335331 }
336-
337- this . _deferToConnect ( null , null , ( ) => this . _flush ( ) ) ;
338332}
339333ObjectSetPrototypeOf ( ClientRequest . prototype , OutgoingMessage . prototype ) ;
340334ObjectSetPrototypeOf ( ClientRequest , OutgoingMessage ) ;
@@ -827,6 +821,7 @@ function onSocketNT(req, socket, err) {
827821 _destroy ( req , null , err ) ;
828822 } else {
829823 tickOnSocket ( req , socket ) ;
824+ req . _flush ( ) ;
830825 }
831826}
832827
0 commit comments