1

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!

1 Answer 1

1

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 promisifiedQueryFunction = util.promisify(db.query).bind(db);
    let results = await promisifiedQueryFunction(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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.