1

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()();
});
A Wizard Did It
  • 3,614
  • 4
  • 28
  • 32
  • That's a clever way to do it. I previously decremented a number until I got to zero. – goat Jan 19 '11 at 17:05

2 Answers2

2

Use the parallel function from the async library.

muckabout
  • 1,923
  • 1
  • 19
  • 31
1

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));
  }
}
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • well them all being named async was just an example, they may do five different things. This seems to be doing the exact same thing mine is doing, and the question is more so if there's anything wrong in doing that. – A Wizard Did It Jan 19 '11 at 16:31
  • No, there's nothing wrong. My point is just that you can abstract out the code for running through the sequence and put it in a separate function. Then when you want to do the sequencing, you'd just call the utility. – Pointy Jan 19 '11 at 16:34