【发布时间】:2019-06-16 09:29:04
【问题描述】:
我使用 fetch 来获取数组中每个元素的数据。这些值被推送到一个数组中,我想在获取所有值后返回这些值的最大值。
为此我使用了一个承诺:
async function init() {
await maxWaste(nut0Codes).then(response => {
console.log(response);
});
}
function maxWaste(nutCodes) {
return new Promise(resolve => {
let waste = [];
nutCodes.forEach((element) => {
let query = queryMaxWaste(element);
fetch(address + encodeURIComponent(query))
.then(response => {
return response.json();
})
.then(response => {
waste.push(response.results.bindings[0].wasteGeneration.value);
console.log(waste);
});
});
let maxWaste = Math.max(waste);
resolve(maxWaste);
});
}
我不确定我的错误在哪里,但在提取完成之前解决了:
我从console.log(response) 收到零,但我不知道为什么它不起作用。
任何建议将不胜感激!
【问题讨论】:
-
你永远不会等待你的
fetch。 -
我该怎么做?如果我写
await fetch(...)我得到一个错误 -
你需要在你最后的
.then上解决fetch -
你不能像现在这样写,promise 会在
forEach中丢失。编写一个手动的 for-each 循环,然后您可以等待每个 fetch。 -
实际上经过进一步检查......您需要将这些承诺推送到数组并使用 Promise.all
标签: javascript asynchronous foreach async-await fetch-api