diff --git a/lib/net.js b/lib/net.js index 53095210fdd808..02f91f08c24b43 100644 --- a/lib/net.js +++ b/lib/net.js @@ -768,8 +768,30 @@ function afterWrite(status, handle, req, err) { req.cb.call(self); } - +function connectExFn(self, ex) { + self._destroy(ex); +} function connect(self, address, port, addressType, localAddress, localPort) { + _connect( + self, + address, + port, + addressType, + localAddress, + localPort, + connectExFn + ); +} + +function _connect( + self, + address, + port, + addressType, + localAddress, + localPort, + exFn +) { // TODO return promise from Socket.prototype.connect which // wraps _connectReq. @@ -800,7 +822,7 @@ function connect(self, address, port, addressType, localAddress, localPort) { if (err) { var ex = exceptionWithHostPort(err, 'bind', localAddress, localPort); - self._destroy(ex); + exFn(self, ex); return; } } @@ -832,7 +854,7 @@ function connect(self, address, port, addressType, localAddress, localPort) { } var ex = exceptionWithHostPort(err, 'connect', address, port, details); - self._destroy(ex); + exFn(self, ex); } } @@ -898,7 +920,6 @@ Socket.prototype.connect = function(options, cb) { return self; }; - function lookupAndConnect(self, options) { const dns = require('dns'); var host = options.host || 'localhost'; @@ -924,7 +945,15 @@ function lookupAndConnect(self, options) { // TODO(evanlucas) should we hot path this for localhost? var addressType = exports.isIP(host); if (addressType) { - connect(self, host, port, addressType, localAddress, localPort); + _connect( + self, + host, + port, + addressType, + localAddress, + localPort, + connectTickError + ); return; } @@ -959,20 +988,31 @@ function lookupAndConnect(self, options) { err.host = options.host; err.port = options.port; err.message = err.message + ' ' + options.host + ':' + options.port; - process.nextTick(connectErrorNT, self, err); + connectTickError(self, err); } else { self._unrefTimer(); - connect(self, + _connect(self, ip, port, addressType, localAddress, - localPort); + localPort, + connectTickError); } }); } +function connectTickError(self, err) { + // wow...http client onSocket registers on processNextTick + // but this registering is executed after this nextTick function. + // so we need to wrap it in one more nextTick :| + process.nextTick(function() { + process.nextTick(connectErrorNT, self, err); + }); +} + + function connectErrorNT(self, err) { self.emit('error', err); self._destroy();