单击按钮后,它将调用以下检查函数,该函数将调用isReady()函数,该函数会执行一些操作以查明是否为真。

当我检查时,isReady()方法实际上返回false,但是它在控制台中返回Success,看来它不等待异步调用完成。

async check() {

   if(await this.isReady(this.entireSchool))
   {
      console.log ("Success")
   }
   else
   {
      console.log ("Fail")
   }
}

async isReady(classes: Class)
{
  // does not include code here,
  //during the test it returns false, it has been confirmed.
}

最佳答案

我也无法重现此问题–如果isReady返回false,则check将在控制台中显示“失败”。



async function isReady() {
  return new Promise((resolve, reject) => {
      window.setTimeout(() => resolve(false), 1000);
    });
}

async function check() {
  if (await isReady()) {
    console.log("success");
  } else {
    console.log("fail");
  }
}

check();

关于javascript - 在if条件下的异步操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54225909/

10-12 22:08
查看更多