我在 for 循环
中有一个 Angular 服务
,它返回一个对象数组。我想获得该服务返回的值的总和,但最终我什么也没得到。我的服务工作正常,但我的问题是我无法得到总和。下面是我的代码
Controller
var TotalOBValueLand = 0;
for(var i = 0; i < $scope.selectedProp.length; i++){
AccountService.getTopAccountDetails($scope.selectedProp[i]["propId"]).then(function(msg){
TotalOBValueLand += parseInt(msg.data[0].OBValueLand);
//my return data here has no error.
});
}
console.log(TotalOBValueLand); //I got zero;
最佳答案
使用 Promise.all
和 array#map
获取结果数组,然后使用 Array#reduce 对它们求和
var TotalOBValueLand = 0;
Promise.all($scope.selectedProp.map(function(prop) {
return AccountService.getTopAccountDetails(prop).then(function(msg){
return parseInt(msg.data[0].OBValueLand);
});
})).then(function(results) {
TotalOBValueLand = results.reduce(function(a, b) {
return a + b;
});
console.log(TotalOBValueLand);
});
In response to the comments
var TotalOBValueLand = 0;
var TotalOBValueBuilding = 0;
Promise.all($scope.selectedProp.map(function(prop) {
return AccountService.getTopAccountDetails(prop).then(function(msg){
return parseInt(msg.data[0]);
});
})).then(function(results) {
TotalOBValueLand = results.reduce(function(a, b) {
return a.OBValueLand + b.OBValueLand;
});
TotalOBValueBuilding = results.reduce(function(a, b) {
return a.OBValueBuilding + b.OBValueBuilding ;
});
console.log(TotalOBValueLand, TotalOBValueBuilding);
});
and a little more generic
Promise.all($scope.selectedProp.map(function(prop) {
return AccountService.getTopAccountDetails(prop).then(function(msg){
return parseInt(msg.data[0]);
});
})).then(function(results) {
var totals = results.reduce(function(result, a) {
Object.keys(a).forEach(function(key) {
result[key] = (result[key] || 0) + a[key];
});
return result;
}, {});
console.log(totals.OBValueLand, totals.OBValueBuilding);
});
关于javascript - for循环中无法求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263624/