我无法执行承诺循环。
我进行服务调用以获取提供商列表,然后为每个提供商进行另一个服务调用以获取客户。
提供商有 1 个或多个客户。因此,最终的客户列表将被装饰和显示。
以其他格式,我正在尝试实现:
*serviceA.getProvider(){
foreach(providers){
foreach(provider.customerID){
serviceB.getCustomer(customerId)
}
}
}
.then(
foreach(Customer){
updateTheCustomer;
addUpdatedCustomerToAList
}
displayUpdatedCustomreList();
)*
我写了以下代码,但不起作用
doTheJob(model: Object) {
let A = [];
let B = [];
let fetchP = function(obj) {
obj.Service1.fetchAllP().then(function (response) {
let P = cloneDeep(response.data);
_.forEach(P, function(prov) {
_.forEach(prov.CIds, function(Id) {
A.push(Id);
});
});
_.forEach(A, function(CId) {
return obj.Service2.getById(CId);//what works is if this statement was: return obj.Service2.getById(A[0]);
//So, clearly, returning promise inside loop isn't working
});
})
.then(function(response) {
B.push(response.data); //This response is undefined
angular.forEach(B, function (value) {
obj.updateAdr(value)
});
obj.dispay(B);
});
};
fetchP(this);
}
>forEach
当你在里面使用return
时不要停止,试着使用普通循环代替,为什么你不只循环for
?
_.forEach(A, function(CId) {
return obj.Service2.getById(CId);
}
如 @Ze Rubeus 所述,如果您在 for 循环中的回调中返回该值,该值将丢失,因为它不会返回给调用方。
可能你想要这样的东西
return Promise.all(A.map(function(CId){
//collect each promise inside an array that will then be resolved
return obj.Service2.getById(CId);
})