Skip to content Skip to sidebar Skip to footer

Multiple Asynchronous Callbacks - Using An Array To Fire Function When Complete

I'm using Node.js and making multiple Asynchronous calls that I need to handle data with when they all finish. I was nesting them, but this was really inefficient as one wouldn't s

Solution 1:

Use the parallel function from the async library.

Solution 2:

Can't you define a function that works its way through the array?

functionasyncSequence(callbacks) {
  functiondoAsync() {
    async(function() {
      if (!callbacks.length) return;
      callbacks[0]();
      callbacks = callbacks.slice(1);
      setTimeout(doAsync, 0);
    });
  }
  doAsync();
}

Then you call that with your array of callback functions.

Now, if you want to launch all the asynchronous callbacks concurrently, then I don't see the problem in the first place; just start them as necessary. If you need to do a sort of "join" at the end of all of them, however, then you'd have to keep track of the general status:

functionasyncSequenceConcurrent(callbacks, whenFinished) {
  var incomplete = callbacks.length;
  for (var i = 0; i < callbacks.length; ++i) {
    async((function(i) {
      returnfunction() {
        callbacks[i]();
        incomplete--;
        if (!incomplete) {
          whenFinished();
        }
      };
    })(i));
  }
}

Post a Comment for "Multiple Asynchronous Callbacks - Using An Array To Fire Function When Complete"