return 从异步函数调用非异步函数时无法正常工作

return not working properly when calling non-async function from async function

我正在尝试进行验证,应用程序每 2 秒检查一次数据库中的某个值,直到找到该值

let conf = false;
do {
  await this.sleep(2 * 1000);
  conf = this.checkSession(hash);
  console.log(conf);
} while (!conf);    
checkSessao(hash) {
  let sql = "SELECT usuario_id FROM sessao WHERE hash='" + hash + "';";

  this.db.selectGenerico(sql).then(response => {
    if (response[0].usuario_id !== null) {
      console.log("suposed to return true");
      return true;
    }

  }).catch(ex => {
    return false;
  });

  return false;
}

事实是,函数总是 return false,即使 console.log("suposed to return true"); 触发。我相信这与我在 async 函数中调用 non-async 函数有关。有什么想法吗?

你的假设是正确的。您需要在 checkSessao 函数中 return 一个 Promise 并等待它在您的循环中解决。

checkSessao(hash) {
  return new Promise((resolve, reject) => {
    let sql = "SELECT usuario_id FROM sessao WHERE hash='" + hash + "';";    
    this.db.selectGenerico(sql).then(response => {
      if(response[0].usuario_id !== null) {
        console.log("suposed to return true");
        resolve(true);
      } else {
        resolve(false);
      }
    }).catch(ex => {
      resolve(false);
    });
  })
}

用法:

let conf = false;
do {
  await this.sleep(2 * 1000);
  conf = await this.checkSession(hash);
  console.log(conf);
} while (!conf);