1

Using async.parallel or custom control flow,

arr = [1, 2, 3, 4, 5, 3, 2, 3, 4, 5] //arr could be any length

get_something = function(num, cb){
  async_io(num, function (err, results){
        cb()
  });

} 

I want to run get_something() on each member of the array in "parallel". When they're all finished I'd like the callback to get called with the results.

4
  • Really in parallel ? Or just the external asynchronous part in parallel ? Commented Sep 3, 2013 at 15:47
  • @dystroy Well, at the same time, not truly parallel. Commented Sep 3, 2013 at 15:48
  • and does get_something takes a callback and call it ? If not it will be hard... Commented Sep 3, 2013 at 15:48
  • @dystroy it can be made to, sure Commented Sep 3, 2013 at 15:48

1 Answer 1

1

Without async :

var n = arr.length, results = new Array(n), oneIsDone = function(index, result){
   results[index] = result;
   if (--n===0) callback(results);
}
arr.forEach(function(val i){ 
    get_something(val, function(result){
       oneIsDone(i, result);
    });
});

With async :

Using async supposes your asynchronous function accepts a callback returning an error as first argument and the result as second, just like your final callback :

async.parallel(arr, get_something, callback);

If your functions don't follow this norm, you'll have to make some ugly wrappings.

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

3 Comments

Trying to get the results passed into the callback sorted by index. results = [{results from 0}, {results from 1}] Similar to how async.parallel works.
Is result given to the callback you give to get_something ?
so then get_something should get passed arr[i] not i? Is i the index or the value?

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.