目前正在使用 http GET 访问外部 API。单独调用时,响应良好。当放入 for 循环时,有些请求似乎没有响应。
这是 http GET 函数:
function httpGetChunk(url, callback) {
http.get(url, function(resp) {
var body='';
resp.on('data', function(chunk) {
body += chunk; //chunk too large from this response
});
resp.on('end', function() {
var data = JSON.parse(body);
callback(data);
});
resp.on("error", function(e) {
console.log("Got error: " + e.message);
});
});
}
当我在 for 循环中为 5 个不同的 url 调用 GET 函数时,我只得到其中一些的响应。运行它几次,响应将来自调用 url 的不同组合,但不会是所有组合。
有什么见解吗?
编辑 1:为了提供更多信息,我的 for 循环看起来像这样。
for (var i=0;i<5; i++) {
httpGetChunk(someUrl, function(data) {
console.log(data);
});
}
这只会打印出一些响应,而不是全部。
编辑 2: 我已经考虑了有关此线程的所有建议。我现在正在使用异步模块并将并发连接数增加到 20:
http.globalAgent.maxSockets = 20;
以下代码是我目前正在测试的代码:
getMatchStats() 返回一个带有统计数据的游戏“比赛”对象(例如比赛中的击杀、死亡等)
matchIds 是包含匹配的所有 id 键的数组
async.parallel([
getMatchStats(matchIds[0], function (matchData) {
console.log('0');
}),
getMatchStats(matchIds[1], function (matchData) {
console.log('1');
}),
getMatchStats(matchIds[2], function (matchData) {
console.log('2');
}),
getMatchStats(matchIds[3], function (matchData) {
console.log('3');
}),
getMatchStats(matchIds[4], function (matchData) {
console.log('4');
}),
], function(err, result) {
console.log('done');
callback(result);
});
和getMatchStats
function getMatchStats(matchId, callback) {
var url = getMatchStatsUrl(matchId); //gets url based on id
httpGetChunk(url, function(data) {
callback(data);
});
}
同样,async.parallel 永远不会完成,因为只有一些请求有响应。每次我运行它时,响应都会来自不同的匹配组合。有时,它甚至会完成所有请求。
也许我的操作系统对连接数有限制(我在本地主机上测试)?
最佳答案
每个请求都是异步的。因此,如果您使用常规的 for
循环,每个步骤都将同步执行,而不会等待调用回调。你需要的是类似 each
的东西来自 async
的方法模块,例如:
async.each(yourArrayOfUrls, function (url, callback) {
httpGetChunk(url, function(data) {
console.log(data);
callback();
});
}, function (err) {
// if some step produce an error, you can get it here...
});
关于node.js - Nodejs Http请求没有响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28890478/