如何在回调结束时获得通知Promise所有回调样式

时间:2019-07-09 18:10:21

标签: javascript

我有一个需要回调的异步函数

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

1 个答案:

答案 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');
}