1

How to access the results variable outside of the function.


con.query(
    "SELECT * FROM table WHERE particulars = 'data'",
    (error, results) => {
      if (error) {
        return console.error(error.message);
      }
      console.log(results);
    }
  );

Console.log is working fine inside the function but when I return the results variable to use it outside the function I get an undefined variable. I know I should use something like an async function but I can't figure out how to use it in this case.

Thank you in advance.

Dipanshu Chaubey
  • 880
  • 1
  • 9
  • 18

2 Answers2

0

If you need to work with async-await it should be:

async function getParticulars() {
    const results = await con.query("SELECT * FROM table WHERE particulars = 'data'");
   //Process results here 
}

I know my answer is very abstract but it should guide you to the answer. In order to give you more insights about this async code I need to know what library you're using to query the DB. Cheers, sigfried.

0

You could return the results to a variable

const results = con.query(
    "SELECT * FROM table WHERE particulars = 'data'",
    (error, results) => {
      if (error) {
        return console.error(error.message);
      }
      return results
    }
  );
Jazz Jones
  • 11
  • 1