2
0
mirror of https://github.com/tenrok/axios.git synced 2026-06-17 19:21:29 +03:00

Improving logic for handling timeout in node

closes #124
This commit is contained in:
Matt Zabriskie
2016-01-22 16:27:54 -07:00
parent d31ebc4c50
commit 7a16f72895
2 changed files with 47 additions and 3 deletions
+19 -3
View File
@@ -13,6 +13,8 @@ var Buffer = require('buffer').Buffer;
module.exports = function httpAdapter(resolve, reject, config) {
var data = config.data;
var headers = config.headers;
var timer;
var aborted = false;
// Set User-Agent (required by some servers)
// Only set header if it hasn't been set in config
@@ -57,6 +59,12 @@ module.exports = function httpAdapter(resolve, reject, config) {
// Create the request
var transport = parsed.protocol === 'https:' ? https : http;
var req = transport.request(options, function handleResponse(res) {
if (aborted) return;
// Response has been received so kill timer that handles request timeout
clearTimeout(timer);
timer = null;
// uncompress the response body transparently if required
var stream = res;
switch (res.headers['content-encoding']) {
@@ -103,13 +111,21 @@ module.exports = function httpAdapter(resolve, reject, config) {
// Handle errors
req.on('error', function handleRequestError(err) {
if (aborted) return;
reject(err);
});
// Handle request timeout
req.setTimeout(config.timeout, function handleRequestTimeout() {
req.abort();
});
if (config.timeout && !timer) {
timer = setTimeout(function handleRequestTimeout() {
var err = new Error('timeout of ' + config.timeout + 'ms exceeded');
err.timeout = config.timeout;
err.code = 'ECONNABORTED';
req.abort();
reject(err);
aborted = true;
}, config.timeout);
}
// Send the request
req.end(data);