如何使用承诺获得相同键值的总数?

How to get total of same key values using promises?

我有一个具有两个不同值的对象数组,我想要总计或根据键值的这些值。我怎样才能正确地运行?请帮助并提前致谢。

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,
}

除非您的工作流程中存在异步内容,否则您不需要任何 Promises。对于您当前的问题,您只需要将金额添加到对象数组中。这就是 reduce() 的用途。在每个数组上调用 reduce() 以获取总和,并调用 return 一个包含两个结果的对象。

var GetFinancial =  function() {

    /* calculate total for Firsr*/
    let productAdsPaymentEventListArr = [{ "CurrencyAmount": "300" },{ "CurrencyAmount": "200"} ]
    let productAdsTotal = productAdsPaymentEventListArr.reduce((total, current) => total + parseInt(current.CurrencyAmount), 0);

    /* calculate total of second*/
    let productAdsPaymentEventListArr2 = [{ "CurrencyAmount": "30"},{ "CurrencyAmount": "20"} ]
    let productAdsTotal2 = productAdsPaymentEventListArr2.reduce((total, current) => total + parseInt(current.CurrencyAmount), 0);

    return {
        productAdsPaymentTotal : productAdsTotal,
        productAdsPaymentTotal2 :productAdsTotal2,
    }
    
}
let financials = GetFinancial()
// do any further calculations you want with financials 
console.log(financials)