A Wizard Did It
A Wizard Did It

Reputation: 3674

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 start until the previous finished. I came up with this, and just wondering if there's anything blatantly wrong with it:

var f = function(){},
    actualCallback = function() { /* Do real stuff */ },
    callbacks = [f, f, f, f, actualCallback];

aync(function() {
    callbacks.shift()();
});
aync(function() {
    callbacks.shift()();
});
aync(function() {
    callbacks.shift()();
});
aync(function() {
    callbacks.shift()();
});
aync(function() {
    callbacks.shift()();
});

Upvotes: 1

Views: 2844

Answers (2)

muckabout
muckabout

Reputation: 1941

Use the parallel function from the async library.

Upvotes: 2

Pointy
Pointy

Reputation: 413702

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

function asyncSequence(callbacks) {
  function doAsync() {
    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:

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

Upvotes: 1

Related Questions