首页 > 解决方案 > 在执行下一个操作之前等待循环完成

问题描述

我有以下循环正在获取数据,然后将其存储到allVegetables变量中。在记录数组的长度之前,我需要完成循环。使用下面的代码,我的长度为零allVegetables

var allVegetables = [];

for (var i = 0; i < 10; i++) {

  //fetch the next batches of vegetables
  fetch(`https://www.nofrills.ca/api/category/NFR001001002000/products?pageSize=48&pageNumber=${i}&sort=title-asc`, {
    "headers": {
      ...      
    },
    "referrer": "https://www.nofrills.ca/Food/Fruits-%26-Vegetables/Vegetable/c/NFR001001002000?sort=title-asc",
    "referrerPolicy": "no-referrer-when-downgrade",
    "body": null,
    "method": "GET",
    "mode": "cors"
  }).then(
    function (response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }

      response.json().then(function (data) {
        //ad the results of the data to the array
        allVegetables = allVegetables.concat(data.results);
      });
    })
};

console.log("number of vegetables are:", allVegetables.length);

目前日志给我零,我认为这是因为它没有等待循环完成填充数组allVegetables。我还假设我应该使用异步,但我是一个新手,无法弄清楚如何做到这一点

标签: javascriptnode.jsloopsfor-loopasync-await

解决方案


尝试将所有获取请求及其结果存储在一个数组中。这将导致一系列承诺。有了这些承诺,您可以等待所有的完成Promise.all并一次性处理所有响应的输出,并将它们全部存储在allVegetables变量中。

因为您最终会得到一个数组数组,Array.prototype.flat()用于创建一个包含所有可以分配给allVegetables变量的值的数组。

let allVegetables = [];
let iterations = 10;

const requests = Array(iterations).fill().map((_, i) => fetch(`https://www.nofrills.ca/api/category/NFR001001002000/products?pageSize=48&pageNumber=${i}&sort=title-asc`, {
  "headers": {
    ...      
  },
  "referrer": "https://www.nofrills.ca/Food/Fruits-%26-Vegetables/Vegetable/c/NFR001001002000?sort=title-asc",
  "referrerPolicy": "no-referrer-when-downgrade",
  "body": null,
  "method": "GET",
  "mode": "cors"
}).then(response => {
  if (response.status !== 200) {
    throw new Error('Looks like there was a problem with request ${i}. Status Code: ' + response.status);
  }
  return response.json();
}).then(data => {
  return data.results;
});

const responses = Promise.all(requests).then(data => {
  allVegetables = [...allVegetables, ...data.flat()];
}).catch(error => {
  console.log(error);
});

推荐阅读