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

121
Views
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 answers
Answer question

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 Report
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!