我在Node.js中處理異步事件。多個異步http獲取請求
我的應用程序正在執行第一個HTTP GET請求,然後根據響應正文中發現的一些信息循環一定次數。
在每次迭代時,它會調用一個函數,它發送其他HTTP GET請求並返回元素數組中推送的結果。
我的問題是,我想console.log()
所有的http請求完成時的元素數組。這裏是我的代碼:
http.get('mysite.com', function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var last = 5,
elements = [];
for(var i=0; i < last; i++) {
elements.push(myRequest(i));
}
console.log(elements);
// Do some stuff with the elements array after it has been populated
});
}).on('error', function(error) {
console.log(error);
});
var myRequest = function(i) {
http.get('mysite.com/page' + i, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
// Do parsing here
return parsed;
});
}).on('error', function(error) {
console.log(error);
});
};
我想過使用異步模塊,但我不確定如何在此用例中使用它。
在此先感謝!
一個HTTP獲取是由定義的異步。不要真的看到你想做什麼。 – asgoth
我只是想完成所有http請求的結果。 –