我有以下循环,该循环正在提取数据,然后将其存储到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
完成并一次性处理所有响应的输出,并将所有结果存储在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);
});