0

I am using angular's $q promise like this:

$scope.loadingData = true; // show loading spinner in view 
var thingsToProcess = [....];

for(int i = 0; i < thingsToProcess.length; i++) {
    var itemToProcess = thingsToProcess[i];

    makeServiceCallThatReturnsPromise(itemToProcess)
        .then(function(response) {
                   processAndDisplayResponse(response);
         });
}

$loadingData = false; // hide loading spinner

Since the service call promises get queued, the loading indicator goes away before all the data is returned from the service.

How can I keep the loading flag set till all the promises are served?

Racil Hilan
  • 24,690
  • 13
  • 50
  • 55
Professor Chaos
  • 8,850
  • 8
  • 38
  • 54

3 Answers3

3

you can use $q.all() here,

var promises=[];
for(int i=0; i<thingsToProcess.length; i++) {
    var itemToProcess = thingsToProcess[i];

  promises.push(  makeServiceCallThatReturnsPromise(itemToProcess)
        .then(function(response) {
                 //do some work here ?
         }));



}

$q.all(promises).then(function(){
  processAndDisplayResponse(response);
})
Jayantha Lal Sirisena
  • 21,216
  • 11
  • 71
  • 92
2

You can use $q.all() for this.

BobS
  • 2,588
  • 1
  • 15
  • 15
0

I agree $q.all(arrayOfPromises)then(sucessFunction(),failureFunction()).[catch] will assist with this.

 var successFlag = false;

function prosessPromises()
{
     var arrPromises = [];
     angular.forEach(collection, function(item, index) {
         var aPromise = promiseFunction(item);
         arrPromises.push(aPromise);
     });
     $q.all(arrPromises).then(successFunction, failureFunction);
}

 function successFunction(data) {
     successFlag = true;
 };

 function failureFunction(error) {
     successFlag = false;
 };

A small word of caution, if one promise fails then the failureFunction will be called even though all the other/remaining promises succeeded. $q.all failure called

Community
  • 1
  • 1