【问题标题】:Cycling through a list with async call inside循环遍历内部有异步调用的列表
【发布时间】:2022-11-22 13:43:21
【问题描述】:

我有一个 ID 数组,我需要遍历所有 ID,并为数组的每个 ID 进行异步调用以从数据库中检索一个值,然后对收集到的所有值求和。我做了这样的事情

  let quantity = 0;
  for (const id of [1,2,3,4]) {
    const subQuantity = await getSubQuantityById(id);
    quantity += subQuantity;
  }

有没有更优雅和简洁的方法来用 javascript 编写这个?

【问题讨论】:

  • (await Promise.all([1,2,3,4].map(i => getSubQuantityById(id))).reduce((p, c) => p + c, 0)

标签: javascript arrays


【解决方案1】:

完全没问题,因为您的案例包含 async 操作。在这里根本不可能使用forEach

您的 for 循环非常干净。如果你想让它更短,你甚至可以这样做:

let totalQuantity = 0;
for (const id of arrayOfIds) {
  totalQuantity += await getSubQuantityById(id);
}

按原样,它甚至可能比上面使用 += await 更清楚。

可以按照建议改进命名。

我发现 cmets 中建议的以下一个衬里更加神秘,因此不太干净:

(await Promise.all([1,2,3,4].map(i => getSubQuantityById(id))).reduce((p, c) => p + c, 0)

【讨论】:

    【解决方案2】:

    有没有更优雅、更巧妙的方法来用 javascript 编写这个?

    当然,通过将您的输入处理为可迭代的。下面的解决方案使用iter-ops库:

    import {pipeAsync, map, wait, reduce} from 'iter-ops';
    
    const i = pipeAsync(
        [1, 2, 3, 4], // your list of id-s
        map(getSubQuantityById), // remap ids into async requests
        wait(), // resolve requests
        reduce((a, c) => a + c) // calculate the sum
    ); //=> AsyncIterableExt<number>
    

    测试可迭代对象:

    (async function () {
        console.log(await i.first); //=> the sum
    })();
    

    附言我是iter-ops 的作者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      相关资源
      最近更新 更多