我有两个承诺链接如下,
var promise1;
var promise2 = promise1.then(function() {
});
现在我有一个条件,即promise1将根据条件执行,即
if(userid == 123) {
promise1 should execute.
}
在这种特殊情况下如何链接promise1和promise2,因为我总是需要执行promise2?
答案 0 :(得分: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
}
我想你想这样做。 请注意,您需要依赖注入$ q
答案 1 :(得分:0)
我想你会想要以下内容:
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);
})
}