Wait for forEach with a promise inside to finish Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30 pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!jQuery Promise wait tp iterate a array for an Item and return if item foundasynchronously map asynchronous functionExecuting promises in array with Promise.all breaks themJavaScript closure inside loops – simple practical exampleHow to access the correct `this` inside a callback?Does following code wait for forEach to finishAngularJS wait for resource inside .run to finishChaining promises from a foreach loopWait for promises inside Promise.all to finish before resolving itwaiting for promises inside a foreachWaiting for a forEach to finish before return from my promise / functionWait for nested JS promise to finish before resolving original promiseAngular 7 - forEach iteration inside of a promise is executing after the promise resolves. Why?

What happened to Viserion in Season 7?

How to translate "red flag" into Spanish?

Is Bran literally the world's memory?

TV series episode where humans nuke aliens before decrypting their message that states they come in peace

What is the evidence that custom checks in Northern Ireland are going to result in violence?

How to compute a Jacobian using polar coordinates?

France's Public Holidays' Puzzle

What's the difference between using dependency injection with a container and using a service locator?

Was Objective-C really a hindrance to Apple software development?

Processing ADC conversion result: DMA vs Processor Registers

Preserving file and folder permissions with rsync

Why did Israel vote against lifting the American embargo on Cuba?

Is there a way to fake a method response using Mock or Stubs?

Why doesn't the university give past final exams' answers?

false 'Security alert' from Google - every login generates mails from 'no-reply@accounts.google.com'

Bright yellow or light yellow?

What does こした mean?

Will I be more secure with my own router behind my ISP's router?

Where to find documentation for `whois` command options?

What is /etc/mtab in Linux?

When speaking, how do you change your mind mid-sentence?

What were wait-states, and why was it only an issue for PCs?

When I export an AI 300x60 art board it saves with bigger dimensions

Determinant of a matrix with 2 equal rows



Wait for forEach with a promise inside to finish



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30 pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!jQuery Promise wait tp iterate a array for an Item and return if item foundasynchronously map asynchronous functionExecuting promises in array with Promise.all breaks themJavaScript closure inside loops – simple practical exampleHow to access the correct `this` inside a callback?Does following code wait for forEach to finishAngularJS wait for resource inside .run to finishChaining promises from a foreach loopWait for promises inside Promise.all to finish before resolving itwaiting for promises inside a foreachWaiting for a forEach to finish before return from my promise / functionWait for nested JS promise to finish before resolving original promiseAngular 7 - forEach iteration inside of a promise is executing after the promise resolves. Why?



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








8















I have a problem with waiting for my forEach loop, which has a promise inside, to finish. I can't find any real solution, that would make the script wait till the end, before continuing with the execution. I cannot make the someFunction synchronous.



makeTree: function (arr) 
arr.forEach(function (resource)
someModule.someFunction(resource).then(function () //a Promise
//do something with the resource that has been modified with someFunction
);
);
// do something after the loop finishes










share|improve this question
























  • are you using angularjs?

    – Abraham Gnanasingh
    Jul 13 '17 at 13:35

















8















I have a problem with waiting for my forEach loop, which has a promise inside, to finish. I can't find any real solution, that would make the script wait till the end, before continuing with the execution. I cannot make the someFunction synchronous.



makeTree: function (arr) 
arr.forEach(function (resource)
someModule.someFunction(resource).then(function () //a Promise
//do something with the resource that has been modified with someFunction
);
);
// do something after the loop finishes










share|improve this question
























  • are you using angularjs?

    – Abraham Gnanasingh
    Jul 13 '17 at 13:35













8












8








8


3






I have a problem with waiting for my forEach loop, which has a promise inside, to finish. I can't find any real solution, that would make the script wait till the end, before continuing with the execution. I cannot make the someFunction synchronous.



makeTree: function (arr) 
arr.forEach(function (resource)
someModule.someFunction(resource).then(function () //a Promise
//do something with the resource that has been modified with someFunction
);
);
// do something after the loop finishes










share|improve this question
















I have a problem with waiting for my forEach loop, which has a promise inside, to finish. I can't find any real solution, that would make the script wait till the end, before continuing with the execution. I cannot make the someFunction synchronous.



makeTree: function (arr) 
arr.forEach(function (resource)
someModule.someFunction(resource).then(function () //a Promise
//do something with the resource that has been modified with someFunction
);
);
// do something after the loop finishes







javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Aug 17 '18 at 12:47







INbahn

















asked Jul 13 '17 at 13:27









INbahnINbahn

5816




5816












  • are you using angularjs?

    – Abraham Gnanasingh
    Jul 13 '17 at 13:35

















  • are you using angularjs?

    – Abraham Gnanasingh
    Jul 13 '17 at 13:35
















are you using angularjs?

– Abraham Gnanasingh
Jul 13 '17 at 13:35





are you using angularjs?

– Abraham Gnanasingh
Jul 13 '17 at 13:35












2 Answers
2






active

oldest

votes


















14














Instead of forEach() use map() to create an array of promises and then use Promise.all()



let promiseArr = arr.map(function (resource) 
// return the promise to array
return someModule.someFunction(resource).then(function (res) //a Promise
//do something with the resource that has been modified with someFunction
return res;
)
);

Promise.all(promiseArr).then(function(resultsArray)
// do something after the loop finishes
).catch(function(err)
// do something when any of the promises in array are rejected
)





share|improve this answer




















  • 1





    Thanks so much for your answer, I had the same doubt and I didn't want to do with packages or something complex. this is the best response for these cases, very simple and brilliant. again, thanks. regards

    – Makito
    Jun 8 '18 at 0:45











  • Simple and clear to read + maintain: thank you for this solution!

    – Cécile Fecherolle
    Sep 27 '18 at 13:46


















2














Try this,



makeTree: function (arr) 
var promises = [];
arr.forEach(function(resource)
promises.push(someModule.someFunction(resource));
);
Promise.all(promises).then(function(responses)
// responses will come as array of them
// do something after everything finishes
).catch(function(reason)
// catch all the errors
console.log(reason);
);



You can refer this link for more on Promise.all with simple examples.






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',
    autoActivateHeartbeat: false,
    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%2f45082038%2fwait-for-foreach-with-a-promise-inside-to-finish%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    14














    Instead of forEach() use map() to create an array of promises and then use Promise.all()



    let promiseArr = arr.map(function (resource) 
    // return the promise to array
    return someModule.someFunction(resource).then(function (res) //a Promise
    //do something with the resource that has been modified with someFunction
    return res;
    )
    );

    Promise.all(promiseArr).then(function(resultsArray)
    // do something after the loop finishes
    ).catch(function(err)
    // do something when any of the promises in array are rejected
    )





    share|improve this answer




















    • 1





      Thanks so much for your answer, I had the same doubt and I didn't want to do with packages or something complex. this is the best response for these cases, very simple and brilliant. again, thanks. regards

      – Makito
      Jun 8 '18 at 0:45











    • Simple and clear to read + maintain: thank you for this solution!

      – Cécile Fecherolle
      Sep 27 '18 at 13:46















    14














    Instead of forEach() use map() to create an array of promises and then use Promise.all()



    let promiseArr = arr.map(function (resource) 
    // return the promise to array
    return someModule.someFunction(resource).then(function (res) //a Promise
    //do something with the resource that has been modified with someFunction
    return res;
    )
    );

    Promise.all(promiseArr).then(function(resultsArray)
    // do something after the loop finishes
    ).catch(function(err)
    // do something when any of the promises in array are rejected
    )





    share|improve this answer




















    • 1





      Thanks so much for your answer, I had the same doubt and I didn't want to do with packages or something complex. this is the best response for these cases, very simple and brilliant. again, thanks. regards

      – Makito
      Jun 8 '18 at 0:45











    • Simple and clear to read + maintain: thank you for this solution!

      – Cécile Fecherolle
      Sep 27 '18 at 13:46













    14












    14








    14







    Instead of forEach() use map() to create an array of promises and then use Promise.all()



    let promiseArr = arr.map(function (resource) 
    // return the promise to array
    return someModule.someFunction(resource).then(function (res) //a Promise
    //do something with the resource that has been modified with someFunction
    return res;
    )
    );

    Promise.all(promiseArr).then(function(resultsArray)
    // do something after the loop finishes
    ).catch(function(err)
    // do something when any of the promises in array are rejected
    )





    share|improve this answer















    Instead of forEach() use map() to create an array of promises and then use Promise.all()



    let promiseArr = arr.map(function (resource) 
    // return the promise to array
    return someModule.someFunction(resource).then(function (res) //a Promise
    //do something with the resource that has been modified with someFunction
    return res;
    )
    );

    Promise.all(promiseArr).then(function(resultsArray)
    // do something after the loop finishes
    ).catch(function(err)
    // do something when any of the promises in array are rejected
    )






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 6 '18 at 13:25









    ctf0

    4,13542334




    4,13542334










    answered Jul 13 '17 at 13:38









    charlietflcharlietfl

    143k1391126




    143k1391126







    • 1





      Thanks so much for your answer, I had the same doubt and I didn't want to do with packages or something complex. this is the best response for these cases, very simple and brilliant. again, thanks. regards

      – Makito
      Jun 8 '18 at 0:45











    • Simple and clear to read + maintain: thank you for this solution!

      – Cécile Fecherolle
      Sep 27 '18 at 13:46












    • 1





      Thanks so much for your answer, I had the same doubt and I didn't want to do with packages or something complex. this is the best response for these cases, very simple and brilliant. again, thanks. regards

      – Makito
      Jun 8 '18 at 0:45











    • Simple and clear to read + maintain: thank you for this solution!

      – Cécile Fecherolle
      Sep 27 '18 at 13:46







    1




    1





    Thanks so much for your answer, I had the same doubt and I didn't want to do with packages or something complex. this is the best response for these cases, very simple and brilliant. again, thanks. regards

    – Makito
    Jun 8 '18 at 0:45





    Thanks so much for your answer, I had the same doubt and I didn't want to do with packages or something complex. this is the best response for these cases, very simple and brilliant. again, thanks. regards

    – Makito
    Jun 8 '18 at 0:45













    Simple and clear to read + maintain: thank you for this solution!

    – Cécile Fecherolle
    Sep 27 '18 at 13:46





    Simple and clear to read + maintain: thank you for this solution!

    – Cécile Fecherolle
    Sep 27 '18 at 13:46













    2














    Try this,



    makeTree: function (arr) 
    var promises = [];
    arr.forEach(function(resource)
    promises.push(someModule.someFunction(resource));
    );
    Promise.all(promises).then(function(responses)
    // responses will come as array of them
    // do something after everything finishes
    ).catch(function(reason)
    // catch all the errors
    console.log(reason);
    );



    You can refer this link for more on Promise.all with simple examples.






    share|improve this answer





























      2














      Try this,



      makeTree: function (arr) 
      var promises = [];
      arr.forEach(function(resource)
      promises.push(someModule.someFunction(resource));
      );
      Promise.all(promises).then(function(responses)
      // responses will come as array of them
      // do something after everything finishes
      ).catch(function(reason)
      // catch all the errors
      console.log(reason);
      );



      You can refer this link for more on Promise.all with simple examples.






      share|improve this answer



























        2












        2








        2







        Try this,



        makeTree: function (arr) 
        var promises = [];
        arr.forEach(function(resource)
        promises.push(someModule.someFunction(resource));
        );
        Promise.all(promises).then(function(responses)
        // responses will come as array of them
        // do something after everything finishes
        ).catch(function(reason)
        // catch all the errors
        console.log(reason);
        );



        You can refer this link for more on Promise.all with simple examples.






        share|improve this answer















        Try this,



        makeTree: function (arr) 
        var promises = [];
        arr.forEach(function(resource)
        promises.push(someModule.someFunction(resource));
        );
        Promise.all(promises).then(function(responses)
        // responses will come as array of them
        // do something after everything finishes
        ).catch(function(reason)
        // catch all the errors
        console.log(reason);
        );



        You can refer this link for more on Promise.all with simple examples.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jul 13 '17 at 13:50

























        answered Jul 13 '17 at 13:41









        Abraham GnanasinghAbraham Gnanasingh

        402417




        402417



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f45082038%2fwait-for-foreach-with-a-promise-inside-to-finish%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

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현