1

I read the answers to How do I return the response from an asynchronous call?. I am still a little confused why this piece of code isn't working correctly. bool is returning "Promise {pending}", which it should not, since I've put the await keyword there.

db.js:

async function validateUser(username, password) {
  var sql = "SELECT * FROM users WHERE username = ? AND password = ?";
  var values = [username, password];

  let promise = new Promise((resolve, reject) => {
    con.query(sql,values, function(err, results) {
      if (err) throw err;
      if (results.length > 0){
        console.log('true');
        resolve("true");
      }
      else{
        console.log('false');
        reject("false");
      }
    }) 
  });
  let bool = await promise; // wait until the promise resolves (*)
  return bool;
}
jpj
  • 83
  • 1
  • 6
  • `bool` is definitely not a promise. However, the `async function` call `validateUser(…)` will return a promise for the boolean to be returned in the future. Instead, you need to put the `await` on the call where you actually want to use the promise result. – Bergi Aug 30 '20 at 11:36
  • Don't use `throw err` but `reject(err)`! Also, what database library is that? You might not need the `new Promise` wrapper at all. – Bergi Aug 30 '20 at 11:38

2 Answers2

4

async functions always return a promise. So if you try to log the return value of validateUser, it will give you a Promise.

Any non-promise value you return from an async function is implicitly wrapped in a Promise.

You can chain a .then() function to the async function call to get the resolved value.

validateUser(username, password)
  .then(value => console.log(value))
  .catch(error => console.log(error));

Looking at your code, it seems that you don't need an async function at all. You can make validateUser a regular function and just return a promise from the validateUser function.

function validateUser(username, password) {
  var sql = "SELECT * FROM users WHERE username = ? AND password = ?";
  var values = [username, password];

  return new Promise((resolve, reject) => {
    con.query(sql,values, function(err, results) {
      if (err) reject(err);

      if (results.length > 0) resolve("true");
      else reject("false");
    }) 
  });
}

You can also check if the database library you are using provides a Promise based API. If it does, you can just use async-await syntax instead of using a callback version to query the database and wrapping that in a Promise constructor.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
0

You'll also need to await validateUser(...); otherwise you'll get the promise that would eventually resolve.

AKX
  • 152,115
  • 15
  • 115
  • 172