我想做的是等待第二个承诺完成,连接数据,即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;
}
});
谢谢!
保持 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);
@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);
}
})
}