Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

346
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda