0

I have an async function that takes a callback

function doAsync(delay, cb) {
  setTimeout(() => {
    console.log('async ', delay);
    cb();
  }, delay);
}

I want to call this function a number of times and be notified when all callbacks are done.

// 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
eguneys
  • 6,028
  • 7
  • 31
  • 63
  • a) switch to promises, they're much better! b) use the `async.js` library which has helper functions for asynchronous iteration – Bergi Jul 09 '19 at 18:39

1 Answers1

0

You need to pass and check the last index with the array's length. I have added that implementation in your code.

Hope this will help you!

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');
}
eguneys
  • 6,028
  • 7
  • 31
  • 63
BadPiggie
  • 5,471
  • 1
  • 14
  • 28