Nodejs Http请求没有响应

目前使用http GET到外部API。 当被单独调用时,响应是好的。 当放在for循环中时,有些请求似乎没有响应。

这是http GETfunction:

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:我已经考虑到了这个线程的所有build议。 我现在正在使用asynchronous模块并将并发连接的数量增加到20:

 http.globalAgent.maxSockets = 20; 

以下代码是当前正在testing的代码:

getMatchStats()返回一个包含统计数据的游戏“匹配”对象(比如杀死,比赛中的死亡等)

matchIds是包含所有匹配的密钥的数组

 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永远不会完成,因为只有一些请求有回应。 每当我运行它,反应将来自不同的比赛组合。 有时甚至完成了所有的要求。

也许我的操作系统有限制的连接数(即时testing本地主机)?

每个请求都是asynchronous的。 所以,如果你使用一个普通的for循环,每一步都将被同步执行,不会等待callback被调用。 你需要什么样的东西像async模块的each方法,如:

 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... });