0

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'.

  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Lawrence Cherone Apr 09 '23 at 13:53

2 Answers2

0

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.

const getAns = (uname) => {
    return new Promise((resolve, reject) => {
        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) reject(err);
          return resolve(rows[0].ans);
        });
    });
};

That way you can just await it in your code

const getData = async () => {
    //You should probably try/catch it
    const ans = await getAns();
    console.log(ans)
}
AlanOnym
  • 131
  • 4
-1

When you are calling db.query function you are passing a callback as the third parameter which returns the row[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.

const getAns = (uname,callback) => {
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;
callback(rows[0].ans)
});
};
Vedant Gandhi
  • 39
  • 1
  • 9