@@ -36,6 +36,7 @@ const { |
36 | 36 | const net = require('net'); |
37 | 37 | const url = require('url'); |
38 | 38 | const assert = require('internal/assert'); |
| 39 | +const { once } = require('internal/util'); |
39 | 40 | const { |
40 | 41 | _checkIsHttpToken: checkIsHttpToken, |
41 | 42 | debug, |
@@ -236,8 +237,6 @@ function ClientRequest(input, options, cb) { |
236 | 237 | this.host = host; |
237 | 238 | this.protocol = protocol; |
238 | 239 |
|
239 | | - let called = false; |
240 | | - |
241 | 240 | if (this.agent) { |
242 | 241 | // If there is an agent we should default to Connection:keep-alive, |
243 | 242 | // but only if the Agent will actually reuse the connection! |
@@ -301,18 +300,6 @@ function ClientRequest(input, options, cb) { |
301 | 300 | options.headers); |
302 | 301 | } |
303 | 302 |
|
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 | | - |
316 | 303 | // initiate connection |
317 | 304 | if (this.agent) { |
318 | 305 | this.agent.addRequest(this, options); |
@@ -321,20 +308,27 @@ function ClientRequest(input, options, cb) { |
321 | 308 | this._last = true; |
322 | 309 | this.shouldKeepAlive = false; |
323 | 310 | 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); |
330 | 326 | } |
331 | 327 | } else { |
332 | 328 | debug('CLIENT use net.createConnection', options); |
333 | 329 | this.onSocket(net.createConnection(options)); |
334 | 330 | } |
335 | 331 | } |
336 | | - |
337 | | - this._deferToConnect(null, null, () => this._flush()); |
338 | 332 | } |
339 | 333 | ObjectSetPrototypeOf(ClientRequest.prototype, OutgoingMessage.prototype); |
340 | 334 | ObjectSetPrototypeOf(ClientRequest, OutgoingMessage); |
@@ -827,6 +821,7 @@ function onSocketNT(req, socket, err) { |
827 | 821 | _destroy(req, null, err); |
828 | 822 | } else { |
829 | 823 | tickOnSocket(req, socket); |
| 824 | + req._flush(); |
830 | 825 | } |
831 | 826 | } |
832 | 827 |
|
|