【发布时间】:2020-04-28 18:52:40
【问题描述】:
我有以下循环获取数据,然后将其存储到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。我还假设我应该使用异步,但我是新手,不知道如何做到这一点
【问题讨论】:
标签: javascript node.js loops for-loop async-await