等待循环完成,然后再执行下一个操作

时间:2020-04-28 18:52:40

标签: javascript node.js loops for-loop async-await

我有以下循环,该循环正在提取数据,然后将其存储到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的填充。我还假设我应该使用异步,但我是新手,无法弄清楚该怎么做

2 个答案:

答案 0 :(得分:1)

尝试将所有提取请求及其结果存储在数组中。这将产生一系列承诺。有了这些承诺,您可以等待所有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);
});

答案 1 :(得分:0)

您可以将所有获取承诺存储在数组中,然后使用Promise.allSettled等待它们完成工作。

这是一个简单的例子:

const responses = [];
for (let i = 0; i < 4; i++) {
  responses.push(
    fetch("https://jsonplaceholder.typicode.com/posts/1").then(response =>
      response.json()
    )
  );
}
Promise.allSettled(responses).then(console.log);

这将记录具有以下形状的对象数组:

{
  status: 'string',
  value: Object
}

作为'value'属性,其中包含从提取中获取的信息。

对于您而言,您只需要检查数组的长度即可。

您可以在sandbox上查看示例。