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

JavaScript中遍历ID数组异步调用求和的更优雅简洁写法?

更优雅的异步求和实现方式

你原来的代码是串行执行每个异步请求,虽然逻辑正确,但效率偏低——每个请求都要等上一个完成才能发起。可以用Promise.all并行处理所有异步调用,既提升性能,代码也更简洁:

const ids = [1, 2, 3, 4];
// 并行发起所有异步请求
const subQuantities = await Promise.all(ids.map(id => getSubQuantityById(id)));
// 对结果数组求和
const totalQuantity = subQuantities.reduce((total, num) => total + num, 0);

补充说明

  • Promise.all会同时触发所有getSubQuantityById调用,等全部请求完成后返回结果数组,相比串行执行能节省大量等待时间。
  • 若要处理单个请求失败的情况,可以改用Promise.allSettled,之后过滤出成功的结果再求和,比如:
const results = await Promise.allSettled(ids.map(id => getSubQuantityById(id)));
const totalQuantity = results
  .filter(res => res.status === 'fulfilled')
  .reduce((total, res) => total + res.value, 0);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 08:10:28