Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Foreach callback when finish [duplicate]

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.
like image 237
Luciano Nascimento Avatar asked Jul 02 '15 19:07

Luciano Nascimento


People also ask

What happens if you return in a forEach?

Using return in a forEach() is equivalent to a continue in a conventional loop.

Does return break out of forEach?

'return' doesn't stop looping The reason is that we are passing a callback function in our forEach function, which behaves just like a normal function and is applied to each element no matter if we return from one i.e. when element is 2 in our case.

Is forEach callback function?

forEach() calls a provided callbackFn function once for each element in an array in ascending index order.

Does JavaScript wait for forEach to finish?

forEach loop is not asynchronous. The Array. prototype. forEach method accepts a callback as an argument which can be an asynchronous function, but the forEach method will not wait for any promises to be resolved before moving onto the next iteration.


2 Answers

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
         }
    });
});
like image 200
Anoop Avatar answered Sep 22 '22 14:09

Anoop


Try this :

myArray.forEach(function(element, index, array){
  asynchronous(function(data){
       if (index === myArray.length - 1) {
           response.push(data);
           functionAfterForEach();
       }
  })
});
like image 39
PaulShovan Avatar answered Sep 19 '22 14:09

PaulShovan