Best way to wait for .forEach() to complete


Sometimes I need to wait for a .forEach() method to finish, mostly on ‘loader’ functions. This is the way I do that:

    //iterate on something 
    //continue with processing 

I can’t help but feel that this isn’t the best way to wait for a .forEach() to finish. What is the best way to do this?


If there is no asynchronous code inside the forEach, forEach is not asynchronous, for example in this code:

    //iterate on something 
alert("Foreach DONE !");

you will see the alert after forEach finished.

Otherwise (You have something asynchronous inside), you can wrap the forEach loop in a Promise:

var bar = new Promise((resolve, reject) => {
    foo.forEach((value, index, array) => {
        if (index === array.length -1) resolve();

bar.then(() => {
    console.log('All done!');

Credit: @rolando-benjamin-vaz-ferreira

Answered By – Ismail RBOUH

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published