嗨,如何在“for of()”循环中对从“async”函数的“then()”返回的“结果”求和?

问题描述 投票:0回答:1

我正在尝试进行一些计算(

converting currency
),然后
sum
返回的转换货币值作为多种产品的订单总额

这里是 JavaScript 代码的一小段:

let sum = 0;
for (const product of products) {
  let currencyConverter = new CC({
    from: product.currency,
    to: "USD",
    amount: parseFloat(price),
  })
  let result = currencyConverter.convert()
    .then((response) => {
      sum += response;
    })
}
javascript asynchronous async-await promise
1个回答
0
投票

使用

await

let sum = 0

for (const product of products) {
    let currencyConverter = new CC({
        from: product.currency,
        to: "USD",
        amount: parseFloat(price),
    })

    sum += await currencyConverter.convert()
}

为此,包含此代码的函数必须是

async
本身(以及调用此函数的每个函数,依此类推)。一旦代码中的一件事是异步的,它“之上”的所有内容也需要是异步的。另请参阅这个问题

© www.soinside.com 2019 - 2024. All rights reserved.