Why do I get an empty object when a function is invoked in node.js?

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?

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) });
});