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
相关产品推荐
相关产品推荐

