Search code examples
javascriptangularjspromiseqdeferred

How can I make a waterfall Q promises?


let's take this as an example:

  • I have 3 urls in an array urls
  • require function returns a promise which just makes an $http call

this is a working code, but as the array can be '1 to n' this is obviously not what I want. I need the 3 require as a waterfall, not in parallel. in the last promise, I need to resolve a final promise which is the var deferred.

require(urls[0]).then(function () {                            
    require(urls[1]).then(function () {                                
        require(urls[2]).then(function () {                                    
            deferred.resolve();
        });
    });
})

this approach is not working, because this will do all the $http calls in parallel.

var promises = [];
angular.forEach(urls, function (value) {
    promises.push(require(value));
});
$q.all(promises).then(function () {
    deferred.resolve();
});

is there a nice way to do this with a for/cycle?


Solution

  • Create a function to handle the iterations:

    function go (urls) {
        if (urls[0]) {
          require(urls[0]).then(function () {
              go(urls.slice(1));
          });
        }
    }
    
    go(urls);