0

I have this app.get in my node.js Express Server.

  app.get('/api/court/:num', function(req, res, next) {
    var courts = new CourtsHandler;
    if (req.params.num == 0) //get array of all courts
      return res.send(200, courts.courtsAmount());          
  });

which is calling this function:

  this.courtsAmount = function(){
  connection.query('SELECT COUNT(*) AS result from courts', function(err, rows, fields){
      if (err) throw err;
      connection.end();
      console.log(rows[0].result);
      return rows[0].result;
      });
    };

The courtsAmount function is getting called. But in my client-view, I am not getting the reuslt. Instead I am just getting an empty object.

I assume this has to do with the fact that my .query has a callback, and thus res.send sends an empty object before courtsAmount is actually fired.

How can I address this issue?

Praveen Vinny
  • 2,372
  • 6
  • 32
  • 40
lobengula3rd
  • 1,821
  • 4
  • 26
  • 39
  • You won't be able to usefully `return` data from `rows` since `connection.query()` is asynchronous. For more info, checkout http://stackoverflow.com/q/14220321. The example it uses is Ajax with jQuery, but the issue and many of the solutions can be applied to any asynchronous task. – Jonathan Lonowski Aug 03 '13 at 20:33

1 Answers1

1

Your courtsAmount doesn't return anything. Instead you should use a callback inside it (or a promise), to do something like this:

this.courtsAmount = function(callback){
connection.query('SELECT COUNT(*) AS result from courts', function(err, rows, fields){
    if (err) throw err;
    connection.end();
    console.log(rows[0].result);
    callback(rows[0].result);
    });
  };

And

app.get('/api/court/:num', function(req, res, next) {
 var courts = new CourtsHandler;
 if (req.params.num == 0) //get array of all courts
   courts.courtsAmount(function(result) { res.send(200, result) });
});
axelcdv
  • 753
  • 6
  • 18
  • thanks! that sorted it out. could you tell me please why in most of the examples i see, the res.send is allways preceeded by return? in my case there is no need to use the return. and could my problem be addressed with events instead of the callback? – lobengula3rd Aug 04 '13 at 06:44
  • Not sure for the return as I haven't seen the examples, but I'd guess it's because the return assures you the function won't continue after that line. I'm not sure how you'd want to replace callbacks by events. You could use event but you'd still need callbacks I think. If you don't like callbacks you can still switch to promises instead though – axelcdv Aug 04 '13 at 08:28