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()();
});
1
  • That's a clever way to do it. I previously decremented a number until I got to zero. Commented Jan 19, 2011 at 17:05

2 Answers 2

2

Use the parallel function from the async library.

Sign up to request clarification or add additional context in comments.

Comments

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));
  }
}

2 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.