0

I am trying to do a validation where each 2 seconds, the app checks into the database for a certain value, until said value is found

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;
}

the thing is, the function ALWAYS return false, even though console.log("suposed to return true"); fires. I believe its related to the fact that i am calling a non-async function inside a async function. Any ideas?

1 Answer 1

1

Your assumption is correct. You need to return a Promise in your checkSessao function and wait until it's resolved in your loop.

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);
    });
  })
}

Usage:

let conf = false;
do {
  await this.sleep(2 * 1000);
  conf = await this.checkSession(hash);
  console.log(conf);
} while (!conf);
Sign up to request clarification or add additional context in comments.

1 Comment

Correct answer. Would be even clearer mentioning that async/await is syntactic sugar for Promise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.