Reputation: 121
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 ?
Upvotes: 0
Views: 39
Reputation: 1348
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);
})
}
Upvotes: 0
Reputation: 2330
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
Upvotes: 1