如何使用回调,promises,无论需要什么来编写for
循环,所以循环将循环自己,每次向不同的api发出请求,然后将结果汇集到一个数组中我可以把它发送到客户端。
e.g。
var streams = ["foo", "bar", "baz"]
var result = [];
for (var i = 0; i < streams.length; i++) {
// Get Stream Data through api request
// Asynchronously do this so that the loop doesn't have to wait to continue for increased performance
result.push({streamName: "Blah", viewers: 123});
}
// Wait till loop is done and all call backs are back (maybe Promise.all?)
res.json({streamData: result});
我认为不必让循环等待每个get
请求完成,而不是让它们全部运行(显然是为了提高性能)。
我怎么能够做到这一点?感谢。
答案 0 :(得分:0)
我经常使用async库来处理这种情况。以下使用async.each
//don't forget `npm install async --save`
var async = require('async');
var streams = ["foo", "bar", "baz"]
var result = [];
async.each(streams, function(stream, callback){
setTimeout(function(){
result.push({streamName: 'Blah', viewers: 128});
callback();
}, 1000);
//for demo only, use your database call here
//or any kind of async requests you would like,
//just call `callback` without arguments for success,
//or pass argument for error, callback(err);
}, function(err){
if(err) {
res.status(400).send(err);
} else {
res.send({streamData: result});
}
});
这是非常有用的大型图书馆,因此请跟进async.js以了解可能出现的问题