【问题标题】:Async await does not wait for function to finish异步等待不等待函数完成
【发布时间】: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


【解决方案1】:

如果您要编写使用async 的代码,您实际上应该使用async。如果这需要同步运行,您可以在 for 循环中等待。如果您希望它们同时运行,请使用mapPromise.all

async function init() {
  const response = await maxWaste(nut0Codes);
  console.log(response);
}

async function maxWaste(nutCode) {
  const waste = [];

  for (const element in nutCode) {
    const query = queryMaxWaste(element);
    const response = await fetch(address + encodeURIComponent(query));
    const json = await response.json();
    waste.push(json.results.bindings[0].wasteGeneration.value);
    console.log(waste);
  }
  const maxWaste = Math.max(waste);
  return maxWaste;
}

您也可以尝试这样编写它,这样您就不必等待每个响应完成后再运行下一个fetch

async function init() {
  const response = await maxWaste(nut0Codes);
  console.log(response);
}

async function maxWaste(nutCode) {
  const waste = await Promise.all(nutCode.map(async element => {
    const query = queryMaxWaste(element);
    const response = await fetch(address + encodeURIComponent(query));
    const json = await response.json();
    return json.results.bindings[0].wasteGeneration.value;
  }));

  return Math.max(waste);
}

【讨论】:

  • @ViktorG 查看我的编辑,了解同时处理所有请求的方法。
猜你喜欢
  • 2023-03-10
  • 2020-10-04
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-13
  • 2019-11-29
  • 2019-05-31
相关资源
最近更新 更多