javascript - 在执行下一个操作之前等待循环完成
问题描述
我有以下循环正在获取数据,然后将其存储到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);
});
推荐阅读
- python - 为什么我的else语句不执行
- linux - Linux 上 UDP 套接字上的 send、sendto 和 sendmsg 的可能返回值是什么?
- google-sheets - 使用自动填充数组公式进行关键字搜索
- javascript - 更新 Vuex 状态时不显示 V-snackbar
- python - 美丽的汤玻璃门页
- python - 用户警告:从版本 2.2.1 开始,macOS 分发轮中的库文件由 Apple Clang (Xcode_8.3.3) 编译器构建
- python - NameError:名称“计数”未定义
- javascript - Javascript 如何从 CLI 发出噪音
- docker - 在 Docker 场景中将 `/var/run/docker.sock` 挂载到 Docker 中的结果是什么?
- java - 按钮不在我告诉他们的地方