使用与http.get,节点js的asynchronous
我有这个数组与rest-apipath:
var paths = ['path1','path2','path3'];
我想创build一个数组,每个path的结果。 在这种情况下,我使用“ http://www.google.com/index.html ”而不是“path”
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'); }); };
这logging:
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 - -
这不是等待电话完成。 我想一个接一个地看看结果。 我究竟做错了什么?
更改每个到每个 系列 。
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'); }); };
这logging:
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