[英]NodeJS Async - Continue execution for multiple http requests even if some fail
我正在尝试发出多个HTTP请求并累积,使用以下代码在NodeJS中显示结果:
const async = require('async');
const request = require('request');
function httpGet(url, callback) {
const options = {
url : url,
json : true
};
request(options,
function(err, res, body) {
console.log("invoked")
callback(err, body);
}
).on('error', function(err) {
console.log(err)
});
}
const urls= [
"http://1.2.3.4:30500/status/health/summary",
"http://5.6.7.8:30505/status/health/summary"
];
async.map(urls, httpGet, function (err, res){
if (err)
console.log(err);
else
console.log(res);
});
这里的问题是,如果第一个请求( http://1.2.3.4:30500/status/health/summary )失败(例如连接被拒绝等),第二个请求将无法通过。 我知道我犯了一个愚蠢的错误,但找不到它。 任何帮助表示赞赏!
在async.map中,如果其中一个调用将错误传递给其回调,则主回调(用于map函数)将立即被错误调用(这是您的问题)。 为了不因第一个错误而终止,请不要在httpGet中使用err param调用回调。
每个使用async,它接收一个参数列表和一个函数,并与每个元素一起调用该函数,确保在您的httpGet内部出错时调用了回调,而没有err,这将使其余的调用继续进行,即使有些电话有误。 这也可以用于map,但是,我认为更适合您情况的函数是async.each,而不是map,还可以使用eachLimit方法限制并发调用的次数。
检查https://caolan.github.io/async/docs.html#each
const async = require('async');
const request = require('request');
function httpGet(url, callback) {
const options = {
url : url,
json : true
};
request(options,
function(err, res, body) {
if (err){
console.log(err);
callback();
return;
}
console.log("invoked")
callback(null, body);
}
).on('error', function(err) {
console.log(err);
callback();
});
}
const urls= [
"http://1.2.3.4:30500/status/health/summary",
"http://5.6.7.8:30505/status/health/summary"
];
async.each(urls, httpGet, function (err, res) {
}, function (err, res) {
});
如果您希望async.map
不会快速失败,您可以这样做
const async = require('async');
const request = require('request');
function httpGet(url, callback) {
const options = {
url : url,
json : true
};
request(options,
function alwaysReportSuccess(err, res, body) {
callback(null, {
success: !err,
result: err ? err : body
});
}
).on('error', function(err) {
console.log(err)
});
}
const urls= [
"http://1.2.3.4:30500/status/health/summary",
"http://5.6.7.8:30505/status/health/summary"
];
async.map(urls, httpGet, function alwaysOk(_, res){
console.log(res); // will be an array with success flags and results
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.