-1

I'm using mysql with nodejs for the first time and I wish to enter the result from an sql query in my webpage through an asynchronous function. I am able to get the correct result but unable to store it within a variable and then use it as an input value.

I've tried using this but this doesn't provide a viable solution. I tried returning the value as well. Also will it be advisable to process the query outside the async function or inside it?

(async function Ahmedabad() {  
      let i = 'select RegNumber from Details ORDER BY RegNumber DESC LIMIT 1;';
  await  con.query(i, [true], (error, results, fields) => {
    if (error) {
      return console.error(error.message);
    }
    let x = results[0].RegNumber;
    console.log(x);      // <------- Shows correct value
  });
  console.log(x);        // <------- Says x is not defined
})()

I want to store the value into a variable and then use it further.

Sayyam Kapoor
  • 145
  • 2
  • 13
  • "*I've tried using this but this doesn't provide a viable solution.*" Can you elaborate a bit as to why a near-exact duplicate of your question doesn't provide "a viable solution"? – esqew Jul 23 '19 at 04:03
  • Because there is only one answer to that question and that doesn't work either. – Sayyam Kapoor Jul 23 '19 at 04:10
  • Can you elaborate on the statement "*doesn't work*"? It does point out the fact that the code should return a `Promise` object to be handled accordingly. – esqew Jul 23 '19 at 04:12
  • There is probably some error in the way the promises are handled in the answer provided, I keep getting "Cannot read property 'then' of undefined". – Sayyam Kapoor Jul 23 '19 at 04:20

1 Answers1

0

You've defined x in the callback scope, so it's not accessible out of the callback. Try this:

(async function Ahmedabad() {  
      let i = 'select RegNumber from Details ORDER BY RegNumber DESC LIMIT 1;';
  let x;
  await  con.query(i, [true], (error, results, fields) => {
    if (error) {
      return console.error(error.message);
    }
    x = results[0].RegNumber;
    console.log(x);      // <------- Shows correct value
  });
  console.log(x);        // <------- Says x is not defined
})()

But to be honest you should think about the whole design of your code))