我想要做的是等待第二个承诺完成,连接数据,即data = data.concat(items)
,然后递增计数,使循环运行指定的时间。它全部用AngularJS编写。
DataService.getSomeData().then(function(data) {
let count = 1;
while (count < 3) {
if (someCondition) { // It evaluates to true
// Second Promise
DataService.getUserData().then(function(items) {
data = data.concat(items); // --------> this should run before incrementing the count
});
count++;
}
$scope.myData = data;
}
});
谢谢!
答案 0 :(得分:1)
@Aleksey Solovey已经提到了使用$ q.all()的解决方案,还有另一种可以使用的递归方法。
DataService.getSomeData().then(function(data) {
getUserDataRecursion(data,0).then(result=>{
$scope.myData = result;
}).catch(error=>{
console.log("error handle ",error)
})
});
getUserDataRecursion(data,count){
return new Promise((resolve,reject)=>{
if(count<3){
if (someCondition){
DataService.getUserData().then((items) {
data = data.concat(items);
count++;
getUserDataRecursion(data,count),then(()=>{
resolve(data);
})
});
}else{
resolve(data);
}
}else{
resolve(data);
}
})
}
答案 1 :(得分:1)
保持api返回承诺 - 它是最容易处理和最可预测的......
DataService.getSomeData()
.then(someData => {
let count = 1;
const promises = [];
while (count < 3) {
if (someCondition) { // It evaluates to true
promises.push(DataService.getUserData());
count++;
}
}
return $q.all(promises)
.then(data => data.reduce((memo, data) => memo.concat(data), someData));
})
.then(data => $scope.myData = data);