I’m trying to get value which I got from select sql query. But when I return my value, it shows undefined. Sorry I’m new to nodejs.I know it’s an async function but I’m lost here. Tried even assigning it to another value by using a function. but still no luck. Im new to this so sorry about that.
const getAns = (uname) => {
const query = "SELECT ans FROM users WHERE username = ?";
// Value to be inserted
const username = uname;
// Creating queries
db.query(query, username, (err, rows) => {
if (err) throw err;
return rows[0].ans;
});
};
My other code which tries to get value is like this
const getData=()=>{
const ans=getAns();
console.log(ans)
}
When tried above code it shows ‘undefined’.
2
Answers
When you are calling
db.query
function you are passing a callback as the third parameter which returns therow[0].ans
. But function does get called asynchronously as a callback whenever the data arrives from mysql.But your function getAns() does not know any way of storing that result.
So instead what you can do is accept a callback for the getAns() function and invoke that callback inside the callback passed to db.query() with the result.
The solution Vedant Gandhi gives is one way to do it, but in my opinion it can lead very easily to what is called callback hell which might cause some readability issues down the line.
My preferred way to handle that sort of stuff is to wrap it in a promise.
That way you can just await it in your code