You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在for of循环中累加async函数返回的货币转换结果?

正确累加异步货币转换结果的方案

你的代码核心问题在于currencyConverter.convert()是异步操作,then回调会在异步任务完成后才执行,但循环是同步执行的——循环结束时所有异步回调都还没触发,所以最终sum还是初始值0。下面是两种可行的解决方式:

方案一:并行处理(推荐,效率更高)

将所有转换任务转为Promise并收集,用Promise.all等待所有任务完成后统一累加,适合无顺序依赖的场景:

// 收集每个商品的转换Promise
const conversionTasks = products.map(product => {
  const converter = new CC({
    from: product.currency,
    to: "USD",
    amount: parseFloat(product.price), // 注意原代码的price变量应为product.price,否则会报错
  });
  return converter.convert();
});

// 等待所有转换完成后计算总和
Promise.all(conversionTasks)
  .then(results => {
    const total = results.reduce((acc, curr) => acc + curr, 0);
    // 这里处理总额的后续逻辑,比如渲染或提交
    console.log('订单总额(USD):', total);
  })
  .catch(err => {
    console.error('货币转换失败:', err);
  });

方案二:串行处理(适合有顺序要求的场景)

用async/await配合for...of循环,逐个等待转换完成后累加,缺点是会逐个执行任务,效率低于并行:

async function computeOrderTotal() {
  let total = 0;
  for (const product of products) {
    try {
      const converter = new CC({
        from: product.currency,
        to: "USD",
        amount: parseFloat(product.price),
      });
      const convertedAmount = await converter.convert();
      total += convertedAmount;
    } catch (err) {
      console.error(`商品转换失败:`, err);
      // 可根据需求选择跳过该商品或终止流程
    }
  }
  console.log('订单总额(USD):', total);
  return total;
}

// 调用计算函数
computeOrderTotal();

额外注意

原代码中的price变量未关联到当前商品,应该改为product.price,否则会因变量未定义或取到错误值导致计算异常。

内容的提问来源于stack exchange,提问作者yeln

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 07:53:27