skip to Main Content

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


  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)
    });
    };
    
    Login or Signup to reply.
  2. 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)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search