0

So I have been developing a note taking app, and I am having some trouble with displaying the username! Normally you would get a result like this:

con.query('SELECT someVariable FROM someColumn', function (result)  {
  console.log(result)
}) 

But I would like to save the result to a variable like this:

var variable = ''; 
con.query('SELECT someVariable FROM someColumn', function (result)  {
  variable = result
}) 
console.log("Here is some data: " + variable)

But that obviously wouldn't work. So how can I do this???

The point

How would I save a mySQL result to a variable, so it can be used later in my code? Also Im not an experienced developer so you might have to do a bit more explaining that usual, thanks.

Pro Poop
  • 357
  • 5
  • 14
  • Tip: [Sequelize](https://sequelize.org/master/) makes this super easy. – tadman Nov 23 '20 at 21:13
  • 2
    Voting to close - duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – esqew Nov 23 '20 at 21:15

1 Answers1

0

If you're new to Node and/or JavaScript then you've just stumbled on one of the major problems of asynchronous programming. Here's your code as the JavaScript runtime sees it:

// Declare variable

var variable = '';

var callback = function(result) {
  variable = result;
};

// This code runs right away
con.query('SELECT someVariable FROM someColumn', callback);

// Then this code runs
console.log("Here is some data: " + variable);

// Then, a thousand years later (from a CPU's perspective) this callback executes
callback(result);

You can see you're jumping the gun here. You can't depend on any behaviour until the callback has run, or in other words, you need to put any dependent behaviour inside the callback.

Since it's 2020 you can also do this with async and await if you're using a Promise-capable library. Your code could look like:

// Assign variable to the result of the query call, waiting as long as necessary
let variable = await con.query('SELECT someVariable FROM someColumn');

console.log("Here is some data: " + variable);

This will be properly sequenced.

tadman
  • 208,517
  • 23
  • 234
  • 262