【发布时间】:2018-10-18 04:01:28
【问题描述】:
我有一个包含两个不同值的对象数组,并且我想要根据键值总计或这些值。我怎样才能让它正常运行?请提前帮助和感谢。
var GetFinancial = function() {
var promises = [];
fnancialObj = {};
/* calculate total for Firsr*/
let productAdsPaymentEventListArr = [{ "CurrencyAmount": "300" },{ "CurrencyAmount": "200"} ]
let productAdsTotal = 0;
productAdsPaymentEventListArr.forEach(function(productAdsPaymentEventListItem, index) {
let valueType = 'productAdsPaymentTotal'
promises.push(GetFinancialEventWithTotal(productAdsPaymentEventListItem.CurrencyAmount, productAdsTotal, fnancialObj, valueType))
})
/* calculate total of second*/
let productAdsPaymentEventListArr2 = [{ "CurrencyAmount": "30"},{ "CurrencyAmount": "20"} ]
let productAdsTotal2 = 0;
productAdsPaymentEventListArr2.forEach(function(productAdsPaymentEventListItem2, index) {
let valueType = 'productAdsPaymentTotal2'
promises.push(GetFinancialEventWithTotal(productAdsPaymentEventListItem2.CurrencyAmount, productAdsTotal2, fnancialObj, valueType))
})
Promise.all(promises).then(function(result) {
console.log("product update or inserted successfully in all ", result)
resolve(result)
}).catch(function(err) {
console.log("err in update or inserted in all promise", err)
})
}
Promice 定义在这里:
var GetFinancialEventWithTotal = function(chargeComponent, totalCharge, fnancialObj, objectKey) {
return new Promise(function(resolve, reject) {
totalCharge = totalCharge + parseFloat(chargeComponent);
if (totalCharge) {
fnancialObj[objectKey] = totalCharge;
resolve(fnancialObj);
} else {
reject("There an Error")
}
})
}
我想要这样的输出(每个数组的每个值根据键值相加):
fnancialObj={
productAdsPaymentTotal : 500,
productAdsPaymentTotal2 :50,
}
【问题讨论】:
-
但是你覆盖了函数
GetFinancialEventWithTotal。我不明白! -
根据@Ele 的观察,看起来第二个
GetFinancialEventWithTotal并没有做任何异步操作。你为什么要把它包装在一个承诺中? -
我不完全确定您是否需要基于该代码的 any 承诺。
forEachs 是同步的,第二个GetFinancialEventWithTotal函数也是如此。 -
这是一个方法,它会返回promise。 Promise 定义如下。
-
@VishnuChauhan 我们看到了 Promise 的定义,但不清楚为什么要使用 Promise。为什么不直接返回值?
标签: javascript node.js meteor promise es6-promise