0

Is there a way that i could call a Async Method in a loop, put all the results in a array & return the results in the end.

Pseudo Code of what i want to do:

methodThatRunsAsync(callback){
  once completes, invoke callback;
}

anotherMethod (){
var result = [];
for(i=1; i=10; i++){

 methodThatRunsAsync(function(resp){
    result.push(resp);
 });

return result;    }

}

But the value of result is always the default value. How can i trap the results of the async block in a sync block and return the same to the caller.

Looking into Promise framework, but finding it a bit tough to get my head around it. If anyone can please help me understand how to achieve this, psuedo code too would be great.

2
  • 1
    github.com/caolan/async - Has everything you need. Commented Feb 6, 2014 at 8:28
  • Thank You...!! Trying not to use the library, any easy way I could write my own module for this. What would be the design pattern. Commented Feb 6, 2014 at 8:29

1 Answer 1

3

No, you can't return the result, as the calls as asynchronous. Use a callback for that function too, and call it when the last result is added:

function anotherMethod (callback) {
  var result = [];
  var count = 10;
  for(i = 0; i < count; i++) {
    methodThatRunsAsync(function(resp){
      result.push(resp);
      if (result.length == count) {
        callback(result);
      }
    });
  }
}

Note that I changed the loop. The loop that you had would not do any iterations at all.

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

2 Comments

Wow.. that was really simple, thanks a ton. But are there any drawbacks in using this method.
@ErrolDsilva: A limitation is that it relies on all calls resulting in a callback. If the asynchronous method could fail or take too long, you might want to add a timeout and call the callback with the results that you got.

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.