typescript - 如何在 for 循环中等待异步函数?

我有一个异步函数,它遍历一个数组,对每个元素进行另一个异步调用,等待结果。

public async myfetch(parent_id: string): Promise<Record[]> {
  let payload = await this.load(parent_id);
  let records = [];

  await payload.items.forEach(async (item: any) => {
        let child = await this.load_another_api(item.child_id);
        let record = {
               a: child.a,
               b: child.b,
        }
        records.push(record)
  }
  return records;
}

而负载的签名,load_another_api 就像:

public async load(Id: string): Promise<any> {
/// some logic to build requestUrl
        return fetch(requestUrl, options)
            .then((response) => { return response.json(); });
}

但是当我调试时,我看到 myfetch 函数在调用所有 for 循环项之前返回到调用者 load_another_api 并等待结果并填充到 records 数组。

你能告诉我我错过了什么吗?

回答1

您可以改用 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/maphttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all 来执行此操作。像这样的东西:

public async myfetch(parent_id: string): Promise<Record[]> {
  const payload = await this.load(parent_id);

  const promises = payload.items.map((item: any) => 
          this.load_another_api(item.child_id)
              .then((child: any) => ({a: child.a, b: child.b})));

  return Promise.all(promises);
}

相似文章

python - python 猜数字游戏,猜多

我正在学习编程1并且正在做1-100的猜数游戏,我需要一个命令,如果我猜超过100,程序会看到它并告诉我,我不知道我应该如何得到这个答案。我已经猜到我认为该命令会是什么样子以及它最远的地方,但如果我完...

随机推荐

最新文章