0

I have two promises which are chained as below ,

var promise1;

var promise2 = promise1.then(function() {

});

Now I have a condition that promise1 will be executed based on a condition i.e

if(userid == 123) {
   promise1 should execute.
}

How do I chain promise1 and promise2 in this particular case where as I always need promise2 to be executed ?

VishnuNair
  • 121
  • 4
  • 12

2 Answers2

1
var promise1 = yourService.getSomthingAsync();
var promise2;
if(userid == 123){
    promise2 = promise1.then(function() {
    //do something
    var deferred = $q.defer(); // create new promise
    return deferred.$promise;
    }
} else {
  promise2 = $q.defer().$promise;
}

promise2.then(function(result){
    // do something else
}

I think you want to do this. Notice that you will need to dependency inject $q

Arno_Geismar
  • 2,296
  • 1
  • 15
  • 29
0

I guess you would want the following :

var promise1 = asyncPromise();
var promise2 = asyncPromise2();

if(userid === 123){
   promise1
       .then(function(data){
            console.log(data); //data from resolving promise1
            return promise2; //returning a promise to chain
       })
       .then(function(data){ //chaining the promise returned from promise 1
            console.log(data);//data from resolving promise2.
       })
       .catch(function(err){//This catch block will be called for errors in both promise1 or promise 2.
           console.log(err)
       })
}
else{//If userid is not equal resolve promise2
    promise2
        .then(function(data){
             console.log(data);
        })
}
Bala Abhinav
  • 1,328
  • 1
  • 9
  • 15