【问题标题】:return not working properly when calling non-async function from async function从异步函数调用非异步函数时返回无法正常工作
【发布时间】:2019-10-13 09:10:27
【问题描述】:

我正在尝试进行验证,应用程序每 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;
}

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

【问题讨论】:

    标签: angular typescript ionic4


    【解决方案1】:

    你的假设是正确的。您需要在您的 checkSessao 函数中返回一个 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);
    

    【讨论】:

    • 正确答案。更清楚地提到 async/await 是 Promise 的语法糖。
    猜你喜欢
    • 2020-11-08
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    • 2020-03-09
    • 2021-02-20
    • 2015-01-22
    • 2019-08-18
    • 2020-07-13
    相关资源
    最近更新 更多