Errol Dsilva
Errol Dsilva

Reputation: 177

Javascript, NodeJS: Call Asychronous Methods in a Loop & Return Result

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.

Upvotes: 0

Views: 54

Answers (1)

Guffa
Guffa

Reputation: 700342

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.

Upvotes: 3

Related Questions