簡體   English   中英

在執行下一個操作之前等待循環完成

[英]Wait for the loop to finish before performing the next action

我有以下循環獲取數據,然后將其存儲到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 我還假設我應該使用異步,但我是一個新手,無法弄清楚如何做到這一點

嘗試將所有獲取請求及其結果存儲在一個數組中。 這將導致一系列承諾。 有了這些承諾,您可以等待Promise.all完成所有操作,並在單個 go 中處理所有響應的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);
});

您可以將所有 fetch promise 存儲在一個數組中,然后使用 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
}

作為“值”屬性,包含從提取中檢索到的信息。

在您的情況下,您只需檢查數組的長度。

您可以在沙盒上查看示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM