我有一个带有rest-api路径的数组:
var paths = ['path1','path2','path3'];
我想创建一个包含每个路径结果的数组。在这种情况下,我改为使用“http://www.google.com/index.html”代替“路径”
exports.test = function(req, res){
var paths = ['path1','path2','path3'];
var resultArr = [];
async.each(paths, function(path, cb){
console.log('collecting data from: ' + path);
http.get('http://www.google.com/index.html', function(result){
resultArr.push(result);
console.log('Done collecting data from: ' + path);
cb();
});
}, function(){
console.log('Done collecting data from all paths');
res.status(200).send('hello');
});
};
此日志:
Starting server at 127.0.0.1:5000
collecting data from: path1
collecting data from: path2
collecting data from: path3
Done collecting data from: path2
Done collecting data from: path1
Done collecting data from: path3
Done collecting data from all paths
GET /test 304 128.752 ms - -
它不是在等待呼叫完成。我希望逐个获得系列结果。我做错了什么?
答案 0 :(得分:2)
将每个更改为 eachSeries 。
exports.test = function(req, res){
var paths = ['path1','path2','path3'];
var resultArr = [];
async.eachSeries(paths, function(path, cb){
console.log('collecting data from: ' + path);
http.get('http://www.google.com/index.html', function(result){
resultArr.push(result);
console.log('Done collecting data from: ' + path);
cb();
});
}, function(){
console.log('Done collecting data from all paths');
res.status(200).send('hello');
});
};
此日志:
collecting data from: path1
Done collecting data from: path1
collecting data from: path2
Done collecting data from: path2
collecting data from: path3
Done collecting data from: path3
Done collecting data from all paths