Given array of strings, iterate over each and call promise based function, but wait to continue until the previous iteration finishes?

I have an array of strings...

var urls = ["http:/www.google.com", "http:/www.giantbomb.com", "http:/www.stackoverflow.com"]

And I need to call a function that is promise based for each one....however I want to wait for the previous one to finish before calling the next.

_.forEach(urls, function(url){ 
    promiseFunc(url); //BUT IT SHOULD WAIT TO CONTINUE FOR LOOP
});

Is there a good way to achieve this?

I am also using AngularJS.

2 answers

  • answered 2019-07-18 15:02 T.J. Crowder

    In a modern environment, use an async function and a loop:

    // In an `async` function
    try {
        for (const entry of urls) {
            await promiseFunc(url);
        }
        // All done
    } catch (error) {
        // Handle/report error
    }
    

    If you don't want to use an async function, use the "promise reduce" trick:

    urls.reduce(
        (p, url) => p.then(() => promiseFunc(url)),
        Promise.resolve()
    )
    .then(() => {
        // All done
    })
    .catch(error => {
        // Handle/report error
    });
    

  • answered 2019-07-18 15:24 user2052752

    I figured out another solution as well with recursion.

    var urls = ["http:/www.google.com", "http:/www.giantbomb.com", "http:/www.stackoverflow.com"];
    var executePromiseFunct: function(urls) {
      promiseFunc(urls[0]).then(function() {
        urls.shift();
        if (urls[0]) {
          executePromiseFunct(urls);
        }
      });
    }