Home > Enterprise >  Express and Mysql2 returning results from db query
Express and Mysql2 returning results from db query

Time:12-23

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!

CodePudding user response:

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

  • Related