简体   繁体   中英

Promise with await returning pending

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM