0

I get some data from the database, but now I want to pass them to another variable. This variable is above getData function.

var storeData;
function getData () {
  connection.connect();
  var query = connection.query('SELECT * FROM users', function(err, results) {
    if(err) throw err;
    console.log(results); // Here is OK. I have all data (results is typeof object)
    storeData = results; // Not working
  });
  connection.end();
}
getData ();
console.log(storeData); // undefined
Vlad Ivanov
  • 111
  • 1
  • 7
  • The "not working" line isn't the problem, the problem is timing; see the linked question's answers. In addition to that issue, you probably don't want to call `connection.end()` **before** the query completes, which is what the above does. Move that call into the completion callback. – T.J. Crowder Jan 02 '17 at 10:42
  • As @T.J.Crowder stated above "the problem is timing". It would seem so that connection.query is async, so, storeData will probably have the value some time later after you logged it out. You can decide to use storeData in the connection.query callback or wrap connection.query in a promise then make use of it. – Ademola Adegbuyi Jan 02 '17 at 10:50

0 Answers0