Reputation: 83
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;
}
Upvotes: 1
Views: 597
Reputation: 29282
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.
Upvotes: 4
Reputation: 168824
You'll also need to await validateUser(...)
; otherwise you'll get the promise that would eventually resolve.
Upvotes: 0