Best way to wait for .forEach() to complete









up vote
4
down vote

favorite
1












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



$q.when(array.forEach(function(item) 
//iterate on something
)).then(function()
//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?










share|improve this question



























    up vote
    4
    down vote

    favorite
    1












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



    $q.when(array.forEach(function(item) 
    //iterate on something
    )).then(function()
    //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?










    share|improve this question

























      up vote
      4
      down vote

      favorite
      1









      up vote
      4
      down vote

      favorite
      1






      1





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



      $q.when(array.forEach(function(item) 
      //iterate on something
      )).then(function()
      //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?










      share|improve this question















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



      $q.when(array.forEach(function(item) 
      //iterate on something
      )).then(function()
      //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?







      javascript angularjs






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jul 16 '16 at 1:47









      Rob

      11.4k82852




      11.4k82852










      asked Jul 16 '16 at 1:41









      Jaap Weijland

      6721819




      6721819






















          4 Answers
          4






          active

          oldest

          votes

















          up vote
          4
          down vote



          accepted










          forEach is not asynchronous, for example in this code:



          array.forEach(function(item) 
          //iterate on something
          );
          alert("Foreach DONE !");


          you will see the alert after forEach finished.






          share|improve this answer
















          • 5




            This is OK if there is no async processing inside the loop.
            – jarmod
            Apr 4 at 16:51










          • @jarmod you are absolutely right ;)
            – Ismail RBOUH
            Apr 4 at 17:09

















          up vote
          10
          down vote













          var foo = [1,2,3,4,5,6,7,8,9,10];


          If you're actually doing async stuff inside the loop, you can wrap it in a promise ...



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

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





          share|improve this answer



























            up vote
            0
            down vote













            The quickest way to make this work using ES6 would be just to use a for..of loop.



            const myAsyncLoopFunction = async (array) 
            const allAsyncResults =

            for (const item of array)
            const asnycResult = await asyncFunction(item)
            allAsyncResults.push(asyncResult)


            return allAsyncResults



            Or you could loop over all these async requests in parallel using Promise.all() like this:



            const myAsyncLoopFunction = async (array) 
            const promises = array.map(asyncFunction)
            await Promise.all(promises)
            console.log(`All async tasks complete!`)






            share|improve this answer



























              up vote
              -3
              down vote













              No, it is blocking. Have a look at the specification of the algorithm.



              So whatever the code which you put outside forEach will execute once foEach() is done.



              array.forEach(function(item) 
              //iterate on something
              )
              // @TODO this code will be executed once above block is done.





              share|improve this answer




















                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38406920%2fbest-way-to-wait-for-foreach-to-complete%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                4
                down vote



                accepted










                forEach is not asynchronous, for example in this code:



                array.forEach(function(item) 
                //iterate on something
                );
                alert("Foreach DONE !");


                you will see the alert after forEach finished.






                share|improve this answer
















                • 5




                  This is OK if there is no async processing inside the loop.
                  – jarmod
                  Apr 4 at 16:51










                • @jarmod you are absolutely right ;)
                  – Ismail RBOUH
                  Apr 4 at 17:09














                up vote
                4
                down vote



                accepted










                forEach is not asynchronous, for example in this code:



                array.forEach(function(item) 
                //iterate on something
                );
                alert("Foreach DONE !");


                you will see the alert after forEach finished.






                share|improve this answer
















                • 5




                  This is OK if there is no async processing inside the loop.
                  – jarmod
                  Apr 4 at 16:51










                • @jarmod you are absolutely right ;)
                  – Ismail RBOUH
                  Apr 4 at 17:09












                up vote
                4
                down vote



                accepted







                up vote
                4
                down vote



                accepted






                forEach is not asynchronous, for example in this code:



                array.forEach(function(item) 
                //iterate on something
                );
                alert("Foreach DONE !");


                you will see the alert after forEach finished.






                share|improve this answer












                forEach is not asynchronous, for example in this code:



                array.forEach(function(item) 
                //iterate on something
                );
                alert("Foreach DONE !");


                you will see the alert after forEach finished.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jul 16 '16 at 1:52









                Ismail RBOUH

                7,69711028




                7,69711028







                • 5




                  This is OK if there is no async processing inside the loop.
                  – jarmod
                  Apr 4 at 16:51










                • @jarmod you are absolutely right ;)
                  – Ismail RBOUH
                  Apr 4 at 17:09












                • 5




                  This is OK if there is no async processing inside the loop.
                  – jarmod
                  Apr 4 at 16:51










                • @jarmod you are absolutely right ;)
                  – Ismail RBOUH
                  Apr 4 at 17:09







                5




                5




                This is OK if there is no async processing inside the loop.
                – jarmod
                Apr 4 at 16:51




                This is OK if there is no async processing inside the loop.
                – jarmod
                Apr 4 at 16:51












                @jarmod you are absolutely right ;)
                – Ismail RBOUH
                Apr 4 at 17:09




                @jarmod you are absolutely right ;)
                – Ismail RBOUH
                Apr 4 at 17:09












                up vote
                10
                down vote













                var foo = [1,2,3,4,5,6,7,8,9,10];


                If you're actually doing async stuff inside the loop, you can wrap it in a promise ...



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

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





                share|improve this answer
























                  up vote
                  10
                  down vote













                  var foo = [1,2,3,4,5,6,7,8,9,10];


                  If you're actually doing async stuff inside the loop, you can wrap it in a promise ...



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

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





                  share|improve this answer






















                    up vote
                    10
                    down vote










                    up vote
                    10
                    down vote









                    var foo = [1,2,3,4,5,6,7,8,9,10];


                    If you're actually doing async stuff inside the loop, you can wrap it in a promise ...



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

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





                    share|improve this answer












                    var foo = [1,2,3,4,5,6,7,8,9,10];


                    If you're actually doing async stuff inside the loop, you can wrap it in a promise ...



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

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






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jul 16 '16 at 2:00









                    Rolando Benjamin Vaz Ferreira

                    1266




                    1266




















                        up vote
                        0
                        down vote













                        The quickest way to make this work using ES6 would be just to use a for..of loop.



                        const myAsyncLoopFunction = async (array) 
                        const allAsyncResults =

                        for (const item of array)
                        const asnycResult = await asyncFunction(item)
                        allAsyncResults.push(asyncResult)


                        return allAsyncResults



                        Or you could loop over all these async requests in parallel using Promise.all() like this:



                        const myAsyncLoopFunction = async (array) 
                        const promises = array.map(asyncFunction)
                        await Promise.all(promises)
                        console.log(`All async tasks complete!`)






                        share|improve this answer
























                          up vote
                          0
                          down vote













                          The quickest way to make this work using ES6 would be just to use a for..of loop.



                          const myAsyncLoopFunction = async (array) 
                          const allAsyncResults =

                          for (const item of array)
                          const asnycResult = await asyncFunction(item)
                          allAsyncResults.push(asyncResult)


                          return allAsyncResults



                          Or you could loop over all these async requests in parallel using Promise.all() like this:



                          const myAsyncLoopFunction = async (array) 
                          const promises = array.map(asyncFunction)
                          await Promise.all(promises)
                          console.log(`All async tasks complete!`)






                          share|improve this answer






















                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            The quickest way to make this work using ES6 would be just to use a for..of loop.



                            const myAsyncLoopFunction = async (array) 
                            const allAsyncResults =

                            for (const item of array)
                            const asnycResult = await asyncFunction(item)
                            allAsyncResults.push(asyncResult)


                            return allAsyncResults



                            Or you could loop over all these async requests in parallel using Promise.all() like this:



                            const myAsyncLoopFunction = async (array) 
                            const promises = array.map(asyncFunction)
                            await Promise.all(promises)
                            console.log(`All async tasks complete!`)






                            share|improve this answer












                            The quickest way to make this work using ES6 would be just to use a for..of loop.



                            const myAsyncLoopFunction = async (array) 
                            const allAsyncResults =

                            for (const item of array)
                            const asnycResult = await asyncFunction(item)
                            allAsyncResults.push(asyncResult)


                            return allAsyncResults



                            Or you could loop over all these async requests in parallel using Promise.all() like this:



                            const myAsyncLoopFunction = async (array) 
                            const promises = array.map(asyncFunction)
                            await Promise.all(promises)
                            console.log(`All async tasks complete!`)







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 9 at 20:58









                            Douglas Rosebank

                            17127




                            17127




















                                up vote
                                -3
                                down vote













                                No, it is blocking. Have a look at the specification of the algorithm.



                                So whatever the code which you put outside forEach will execute once foEach() is done.



                                array.forEach(function(item) 
                                //iterate on something
                                )
                                // @TODO this code will be executed once above block is done.





                                share|improve this answer
























                                  up vote
                                  -3
                                  down vote













                                  No, it is blocking. Have a look at the specification of the algorithm.



                                  So whatever the code which you put outside forEach will execute once foEach() is done.



                                  array.forEach(function(item) 
                                  //iterate on something
                                  )
                                  // @TODO this code will be executed once above block is done.





                                  share|improve this answer






















                                    up vote
                                    -3
                                    down vote










                                    up vote
                                    -3
                                    down vote









                                    No, it is blocking. Have a look at the specification of the algorithm.



                                    So whatever the code which you put outside forEach will execute once foEach() is done.



                                    array.forEach(function(item) 
                                    //iterate on something
                                    )
                                    // @TODO this code will be executed once above block is done.





                                    share|improve this answer












                                    No, it is blocking. Have a look at the specification of the algorithm.



                                    So whatever the code which you put outside forEach will execute once foEach() is done.



                                    array.forEach(function(item) 
                                    //iterate on something
                                    )
                                    // @TODO this code will be executed once above block is done.






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jul 16 '16 at 4:10









                                    Suneet Bansal

                                    1,9051613




                                    1,9051613



























                                         

                                        draft saved


                                        draft discarded















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f38406920%2fbest-way-to-wait-for-foreach-to-complete%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Kleinkühnau

                                        Makov (Slowakei)

                                        Deutsches Schauspielhaus