如何在 JavaScript 异步循环方法中推送到数组? [重复]

问题描述 投票:0回答:1

我正在尝试推送到 paths 数组,但它控制台记录了一个空数组。尝试过

Promise.all
但没有成功。

  const paths: Path[] = [];

  Promise.all([
    allCategories[0].forEach(async ({ id }) => {
      const eachCategoryProducts = await getProductsByCategory(id);

      const eachCategoryProductsCount = eachCategoryProducts[1];
      let categoryPages: any;

      const howManyCategoryProducts = eachCategoryProductsCount / limit;
      categoryPages = Math.ceil(howManyCategoryProducts / 1) * 1;

      for (var i = 0; i < categoryPages; i++) {
        paths.push({
          params: { page: `${i + 1}`, main: "category", id },
        });
      }
    }),
  ]).then(() => {
    console.log(paths);
  });

如何使用异步

forEach
循环正确推送路径常量?

javascript arrays asynchronous async-await promise
1个回答
0
投票

您使用

Promise.all
的方式无法正确处理循环的异步性质。

const paths: Path[] = [];

async function processCategory(id: number, limit: number) {
  const eachCategoryProducts = await getProductsByCategory(id);

  const eachCategoryProductsCount = eachCategoryProducts[1];
  let categoryPages: any;

  const howManyCategoryProducts = eachCategoryProductsCount / limit;
  categoryPages = Math.ceil(howManyCategoryProducts / 1) * 1;

  for (var i = 0; i < categoryPages; i++) {
    paths.push({
      params: { page: `${i + 1}`, main: "category", id },
    });
  }
}

(async () => {
  await Promise.all(
    allCategories[0].map(({ id }) => processCategory(id, limit))
  );

  console.log(paths);
})();
© www.soinside.com 2019 - 2024. All rights reserved.