angular $q, How to chain multiple promises within and after a for-loop angular $q, How to chain multiple promises within and after a for-loop angularjs angularjs

angular $q, How to chain multiple promises within and after a for-loop


What you need to use is $q.all which combines a number of promises into one which is only resolved when all the promises are resolved.

In your case you could do something like:

function outerFunction() {    var defer = $q.defer();    var promises = [];    function lastTask(){        writeSome('finish').then( function(){            defer.resolve();        });    }    angular.forEach( $scope.testArray, function(value){        promises.push(writeSome(value));    });    $q.all(promises).then(lastTask);    return defer.promise;}


With the new ES7 you can have the same result in a much more straightforward way:

let promises =  angular.forEach( $scope.testArray, function(value){    writeSome(value);});let results = await Promise.all(promises);console.log(results);


You can use $q and 'reduce' together, to chain the promises.

function setAutoJoin() {    var deferred = $q.defer(), data;    var array = _.map(data, function(g){            return g.id;        });    function waitTillAllCalls(arr) {        return arr.reduce(function(deferred, email) {            return somePromisingFnWhichReturnsDeferredPromise(email);        }, deferred.resolve('done'));    }    waitTillAllCalls(array);    return deferred.promise;}