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

How to push to an array in javascript async loop methods? [duplicate]

提问人:Mehdi Faraji 提问时间:10/31/2023 更新时间:10/31/2023 访问量:49

问:

我正在尝试推送到路径数组,但它控制台记录了一个空数组。尝试过但没有成功。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 数组异 async-await promise

评论


答:

1赞 Ale_Bianco 10/31/2023 #1

您的使用方式无法正确处理循环的异步性质。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);
})();

评论

0赞 Mehdi Faraji 10/31/2023
我怎样才能使用这样的数组形式?''' Promise.all([ allCategories[0].map(({ id }) => processCategory(id, limit)), allSubcategories[0].map(({ id }) => processSubcategory(id, limit)), allBrands[0].map(({ id }) => processBrand(id, limit)), ]).then(() => { console.log(paths); resolve(res, paths);```Promise.all