我有一个需要回调的异步函数
function doAsync(delay, cb) {
setTimeout(() => {
console.log('async ', delay);
cb();
}, delay);
}
我想多次调用此函数,并在所有回调完成后得到通知。
// I have to call `doAsync` for each element of this array
var a = [100,300,200,400];
a.forEach(_ => doAsync(_, () => {}));
function onEnd() {
console.log('all done');
}
// expected output
//
// async 100
// async 200
// async 300
// async 400
// all done
答案 0 :(得分:0)
您需要通过index
并检查最后一个array's length
。我已经在您的代码中添加了该实现。
希望这对您有帮助!
function doAsync(delay, cb, key) {
if ((key + 1) == a.length) {
onEnd();
}
setTimeout(() => {
console.log('async ', delay);
cb();
}, delay);
}
// I have to call `doAsync` for each element of this array
var a = [100,200,400,300];
a.forEach(function(_,k){doAsync(_, () => {},k)});
function onEnd() {
console.log('all done');
}