HanYi Zhang HanYi Zhang - 1 month ago 9
AngularJS Question

$q.All didn't wait for all promises finishes when cascading then

I have been using $q.all for running an array of promise asynchronously. In one of the element of the array, I want to cascade the promise so that I want to finish the whole functions before jumping out to the outest then function. the code looks below:

$q.all([
function1().then(function () { }, function (reason) { addToErrorList($scope, reason) }),
function2().then(function () { }, function (reason) { addToErrorList($scope, reason) }),
function3().then(function () { }, function (reason) { addToErrorList($scope, reason) }),
function4().then(function () { }, function (reason) { addToErrorList($scope, reason) }),
function5($q).then(
function() {
$q.all([
function51($q).then(function () { }, function (reason) { addToErrorList($scope, reason) }),
function52($q).then(function () {
someLogic();
}, function (reason) { addToErrorList($scope, reason); }),
])})
]).then(function () {
usSpinnerService.stop('spinner');

if ($scope.errorList.length > 0) {
showMessages($scope, $scope.errorList, "error");
}
});


It seems like the code went to execute "usSpinnerService.stop('spinner');" before it actually runs into function51 and function52. I am wondering is there anyway to make the outside $q.all to execute all of the functions? Thanks.

And I also found that addToErrorList($scope, reason) in each of the top four functions are run asynchronously. Is there anyway to make it run synchronously then execute the outest then function?

Correction: above paragraph is not correct. I have checked addToErrorList DOES run before outer then function is hit.

Answer

You need to return $q.all here:

function() {
    return $q.all([
        function51($q).then(function () { }, function (reason) { addToErrorList($scope, reason) }),
        function52($q).then(function () {
            someLogic($http, $scope, $q, sharedService);
        }, function (reason) { addToErrorList($scope, reason); }),
    ])})
Comments