首页 > 解决方案 > 异步未正确等待

问题描述

我知道这已经被问过很多次了,但到目前为止我找到的答案似乎都不适用于我的特定问题。我正在尝试创建一个异步函数,该函数还在其中执行一堆 axios 调用,然后一旦所有这些调用都完成,它就会执行其他操作。

我认为将所有内容都包装在一个异步函数中,然后等待它可以解决问题,但它似乎没有奏效。

let gamesFound = 0;

  mainFn();

  async function mainFn() {
    await loader();
    if (gamesFound == 0) {
      document.getElementById("indexH1").innerHTML = "Oops! We didn't find any data.";
      document.getElementById("introLine").innerHTML = "It doesn't look like there are any games with that time control in the date range, please try changing your filters.";
      document.getElementById("loadingCheck").style.display = "none";
    }
  }

  async function loader() {

    axios.get(url1)
      .then((response) => {
        // Some synchronous code with the response
        axios.get(url1)
          .then((response) => {
            // Some more synchronous code with the response of this
              axios.get(archive)
                .then((response) => {
                  gamesFound++;
                .catch((error) => {
                })
            }
          })
          .catch((error) => {
          })
      })
      .catch((error) => {
      })

  }

第一部分似乎工作正常,但实际上loader()似乎在if (gamesFound ==0)评估条件后运行。

标签: javascriptasynchronous

解决方案


推荐阅读