[英]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.