I have written a Promise-based function which works the way I intended, but I could not write a function which works with only using callbacks. I have made the following code which is intended to return the result of a select query:
function getUserByEmail(email) {
let sql = `SELECT * FROM userlogin WHERE Username = ?`;
con.query(sql, email, (err, result) => {
if (!err) {
return result[0]; // callback returns the result
} else {
return err;
}
})
}
In the case of the above code, the function returns undefined, because the higher-order function doesn't return anything, but the callback does.
I then tried the function below, but in this case con.query() returns an object I don't understand, and not having the query result anywhere to be found in its attributes.
function getUserByEmail(email) {
let sql = `SELECT * FROM userlogin WHERE Username = ?`;
let result = con.query(sql, email, (err, result) => {
if (!err) {
return result[0]; // callback returns the result
} else {
return err;
}
});
return result;
}
I am out of ideas, I know that if I could make con.query() return the return value of the callback, I would be able to get the result but how do I do it?
Below is the version of the function I wrote with Promises, which returns the query result as I intended.
function getUserByEmail(email) {
let sql = `SELECT * FROM userlogin WHERE Username = ?`;
return new Promise((resolve, reject) => {
con.query(sql, email, (err, result) => {
if (!err) {
resolve(result[0]);
} else {
console.log(err);
reject(err);
}
})
})
}