9

I want to execute a callback when foreach has finished, but it's not working properly.How can I do that?

var response = [];
myArray.forEach(function(data) {
    data.asyncFunction(function(result) {
         response.push(result);
    });
}, function() {
    console.log(response); // Not being called.
});

console.log(response); // (Empty) Executed before foreach finish.
Luciano Nascimento
  • 2,600
  • 2
  • 44
  • 80

2 Answers2

12

Because forEach accept only one callback. Since you are calling asynchronous method inside forEach you need to check whether all asyn call completed

var response = [];
myArray.forEach(function(data, index) {
    data.asyncFunction(function(result) {
         response.push(result);
         if(response.length  === myArray.length) {
                 //foreach work done
         }
    });
});
Anoop
  • 23,044
  • 10
  • 62
  • 76
4

Try this :

myArray.forEach(function(element, index, array){
  asynchronous(function(data){
       if (index === myArray.length - 1) {
           response.push(data);
           functionAfterForEach();
       }
  })
});
PaulShovan
  • 2,140
  • 1
  • 13
  • 22
  • `myArray` is not changing... so whenever you call for it's length it will give the correct length @Kevin B – PaulShovan Jul 02 '15 at 20:08
  • 1
    the comment was of course to the original iteration of your answer. though, i think it still stands. if the last iteration of the loop finishes anything other than last, you'll call the callback too soon. – Kevin B Jul 02 '15 at 20:09
  • sorry @Kevin B it was a silly mistake for me – PaulShovan Jul 02 '15 at 20:09
  • sorry, see edits to comment. i have a bad habit of hitting enter in comments before i'm done. :) – Kevin B Jul 02 '15 at 20:11