LBA LBA - 5 months ago 50
AngularJS Question

Cannot get $q.all with nested promises working - wait for all

I fully understand that similar questions have been asked before but I don't get it running. I need a chain of promises and I need to wait until all promises are resolved.

My issue is that I need to call different promises based on the outcome of another promise :-(

So based on the outcome of promise2 my promise4 is EITHER $translate.use OR it is $translate.refresh.

This is what I have so far (simplified):




var promise1 = someService.get({}).$promise.then(function (result) {
// do stuff
});

var promise2 = anotherService.getPromise().then(function (result) {
var properties = result[0];
// do stuff
return properties;
});

var promise3 = promise2.then(function(properties){

// using $translate (angular-translate) here which is async as well

var userLanguage = properties.language;
if (userLanguage !== $translate.preferredLanguage()) {
// either this is the 4th promise
$translate.use(userLanguage).then(function (myVar) {
// ...
});
} else {
// or this is the 4th promise
$translate.refresh().then(function (myVar) {
// ...
});
}
});

var loadPromises = {
promise1: promise1
promise2: promise2
promise3: promise3
promise4: ???
};

$q.all(loadPromises).then(function (result) {
// anything done
});




Answer

You don't really need to monitor promise3 and promise4, all you need is promise1 and promise2. promise3 becomes next step of the promise2. Just note how you return new promise (either return $translate.use or return $translate.refresh) from promise2 then part :

var promise1 = someService.get({}).$promise.then(function(result) {
  // do stuff
});

var promise2 = anotherService.getPromise().then(function(result) {
  var properties = result[0];
  // do stuff
  return properties;
})
.then(function(properties) {

  // using $translate (angular-translate) here which is async as well

  var userLanguage = properties.language;
  if (userLanguage !== $translate.preferredLanguage()) {
    // either this is the 4th promise
    return $translate.use(userLanguage).then(function(myVar) {
      // ...
    });
  } else {
    // or this is the 4th promise
    return $translate.refresh().then(function(myVar) {
      // ...
    });
  }
});

var loadPromises = {
  promise1: promise1,
  promise2: promise2
};

$q.all(loadPromises).then(function(result) {
  // anything done
});