简体   繁体   English

Express 和 Mysql2 从数据库查询返回结果

[英]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.我正在尝试从我的 get_salt_and_hash() function 返回结果(json 对象数组)。 I then want to use the results in another function.然后我想在另一个 function 中使用结果。 (In this case the length of the results array is one.) (在这种情况下,结果数组的长度为 1。)

However, after calling the get_salt_and_hash() in my other function, when I try to print the object I get undefined.但是,在我的其他 function 中调用 get_salt_and_hash() 后,当我尝试打印 object 时,我得到了未定义。 I am unsure as to why, since console.log(results) in the original function works.我不确定为什么,因为原始 function 中的 console.log(results) 有效。 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.我怀疑它与异步代码有关,因为进行数据库查询需要时间,但我对异步 javascript 几乎一无所知,所以我认为最好问问其他人。

Thanks in advance!提前致谢!

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().你是对的,从数据库中获取结果需要时间,所以只需承诺 query() function,这样你就可以在 query() function 调用上使用 await,我在下面修改了你的代码并承诺了 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您可以从这里了解如何编写异步函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM