0

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);
        }
    })
})
   
}
Nagusameta
  • 109
  • 8
  • 1
    `getUserByEmail` must either be async or take a callback function that triggers the return. There is no magical way to essentially turn async code to a synchronous result like you are trying to do. – Joe Nov 16 '21 at 04:01
  • 1
    You cannot directly return the response from an asynchronous operation. You must instead return the value via a callback, a promise or an event. See the [question yours has been marked a duplicate of](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call/14220323#14220323) for more explanation. – jfriend00 Nov 16 '21 at 04:13

0 Answers0