Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

347
Views
How to return the result of Node.js mysql2 query() function in non-Promise code?

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);
        }
    })
})
   
}
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!