Working with $q.all to execute an array of promises asynchronously has been my recent task. I encountered a situation where I needed to ensure that one of the elements in the array completes its promise execution before moving on to the outermost 'then' function. Here's a snippet of the code:
$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 appears that the code proceeds to execute "usSpinnerService.stop('spinner');" before completing the tasks in function51 and function52. I am looking for a way to ensure that all functions within the outer $q.all are executed before proceeding. Any suggestions would be appreciated. Thank you.
Additionally, I noticed that the calls to addToErrorList($scope, reason) in the first four functions are executed asynchronously. Is there a way to make them run synchronously before moving on to the outer 'then' function?
Correction: The above paragraph is incorrect. Upon further inspection, I confirmed that addToErrorList does run before reaching the outer 'then' function.