Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

351
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda