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

122
Vistas
Express and Mysql2 returning results from db query

I am trying to return the results (an array of json objects) from my get_salt_and_hash() function. I then want to use the results in another function. (In this case the length of the results array is one.)

However, after calling the get_salt_and_hash() in my other function, when I try to print the object I get undefined. I am unsure as to why, since console.log(results) in the original function works. Could someone help me out.

const get_salt_and_hash = (email) => {
const query = `SELECT p_salt, p_hash FROM USERS_TABLE WHERE email= "${email}"`;
db.query(query, (err, results) => {
    if (!err) {
        console.log(results);
        return results[0];
    } else {
        throw err
    }
})}


const verify_user = (email, password) => {

let result_obj = get_salt_and_hash(email);
console.log(result_obj);
// const p_hash = result_obj['p_hash'];
// const p_salt = result_obj['p_salt']

}

I suspect it has something to do with asynchronous code, since it takes time for the db query to be made, but I pretty much no nothing about async javascript, so I thought it would be better to ask others.

Thanks in advance!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You are correct that, it takes time to fetch results from db, so just promisify the query() function , so you can use await on the query() function call , I modified your code below and promisified the query().

// Not tested.
const util = require('util');

const get_salt_and_hash = async (email) => {
    const query = `SELECT p_salt, p_hash FROM USERS_TABLE WHERE email= "${email}"`;

    const promisifiedQuerFunction = util.promisify(db.query).bind(db);
    let results = await promisifiedQuerFunction(query);
    return results[0];
}

const verify_user = async (email, password) => {

    let result_obj = await get_salt_and_hash(email);
    console.log(result_obj);
}    

You can learn how write async functions from here

about 4 years ago · Juan Pablo Isaza Denunciar
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