From 42f6998828a04d1cf10c6929cb51317df39bbf05 Mon Sep 17 00:00:00 2001 From: Vsevolod Strukchinsky Date: Mon, 16 Jan 2017 18:45:17 +0500 Subject: [PATCH] simplify code (move out socket timeout part) --- index.js | 30 +++++++++++++----------------- 1 file changed, 13 insertions(+), 17 deletions(-) diff --git a/index.js b/index.js index 94007a4..fe5c2fa 100644 --- a/index.js +++ b/index.js @@ -17,16 +17,27 @@ module.exports = function (req, time) { }, delays.connect); } + if (delays.socket !== undefined) { + // Abort the request if there is no activity on the socket for more + // than `delays.socket` milliseconds. + req.setTimeout(delays.socket, function socketTimeoutHandler() { + req.abort(); + var e = new Error('Socket timed out on request' + host); + e.code = 'ESOCKETTIMEDOUT'; + req.emit('error', e); + }); + } + // Clear the connection timeout timer once a socket is assigned to the // request and is connected. req.on('socket', function assign(socket) { // Socket may come from Agent pool and may be already connected. if (!(socket.connecting || socket._connecting)) { - connect(); + clear(); return; } - socket.once('connect', connect); + socket.once('connect', clear); }); function clear() { @@ -36,20 +47,5 @@ module.exports = function (req, time) { } } - function connect() { - clear(); - - if (delays.socket !== undefined) { - // Abort the request if there is no activity on the socket for more - // than `delays.socket` milliseconds. - req.setTimeout(delays.socket, function socketTimeoutHandler() { - req.abort(); - var e = new Error('Socket timed out on request' + host); - e.code = 'ESOCKETTIMEDOUT'; - req.emit('error', e); - }); - } - } - return req.on('error', clear); };