Node MYSQL request, Async issue

Okay, so i could use some help. I know my code is incorrect, whats the easiest way to go about handling this. As you can see my return is going to return an empty variable before the query has been executed.

const fetchall = function fetch(sessionid) {
      let data;
      connection.query(
        'SELECT * FROM LOCATIONS WHERE SESSIONID = ?', [sessionid],
        function(err, rows, fields) {
          data = rows;
      });
      return data;
    }; 

I am using express here and the code for the request looks like this.

  app.post('/api/locations/fetchall', function (req, res) {
    let sesionid = sessions.active();
    let results = locations.fetchall(sesionid);
    res.send(results);
  });

Answers


You have to return data inside the query. I am not sure what module you are using to make your database query. I assume that function(err, rows, fields){} is a callback. That means you have to return data in your query() function and not outside.

Or else, check if your framework is not promise-based, ie. you can call something like

connection.query("your query").then(function(data){
   //return data somewhere in here
})

Need Your Help

android countdown to milliseconds

java android countdowntimer date-formatting

i am trying to make a countdown application, where the maximum time will be under 10 mins, and i would like to have it show as mm:ss:ms (not too sure if ms is the term for milliseconds). and this i...

ie7 display:inline

css internet-explorer-7 internet-explorer-6

I know this question has been asked a hundred times, and I feel like I've looked at all 100 posts, but this is driving me nuts.