处理多个异步回调的最佳方法/库是什么?现在,我有这样的事情:
_.each(stuff, function(thing){
async(thing, callback);
});
我需要在为stuff
中的每个元素触发回调后执行一些代码。
最干净的方法是什么?我愿意使用库。
答案 0 :(得分:28)
由于您已经在使用下划线,因此您可以查看_.after
。它完全符合您的要求。来自文档:
之后_.after(count, function)
创建一个只在首次被调用计数次数后才能运行的函数版本。在继续之前,您可以对异步响应进行分组,以确保所有异步调用都已完成。
答案 1 :(得分:12)
有一个很棒的名为Async.js的库可以帮助解决许多异步和类似的问题。流量控制助手。它提供了几个forEach函数,可以帮助您为数组/对象中的每个项运行回调。
退房: https://github.com/caolan/async#forEach
// will print 1,2,3,4,5,6,7,all done
var arr = [1,2,3,4,5,6,7];
function doSomething(item, done) {
setTimeout(function() {
console.log(item);
done(); // call this when you're done with whatever you're doing
}, 50);
}
async.forEach(arr, doSomething, function(err) {
console.log("all done");
});
答案 2 :(得分:2)
我建议https://github.com/caolan/async。您可以使用async.parallel
执行此操作。
function stuffDoer(thing) {
return function (callback) {
//Do stuff here with thing
callback(null, thing);
}
}
var work = _.map(stuff, stuffDoer)
async.parallel(work, function (error, results) {
//error will be defined if anything passed an error to the callback
//results will be an unordered array of whatever return value if any
//the worker functions passed to the callback
}
答案 3 :(得分:1)
async.parallel()/ async.series应该符合您的要求。您可以提供在所有REST调用成功时执行的最终回调。
async.parallel([
function(){ ... },
function(){ ... }
], callback);
async.series([
function(){ ... },
function(){ ... }
], callback);
答案 4 :(得分:0)
有一个柜台,说async_count
。每次启动请求时(在循环内)将其增加一,并使回调减少一个,并检查是否已达到零 - 如果是,则返回所有回调。
答案 5 :(得分:0)