为什么我得到一个空的对象,当一个函数在node.js中被调用? [英] Why do I get an empty object when a function is invoked in node.js?

查看:112
本文介绍了为什么我得到一个空的对象,当一个函数在node.js中被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的 app.get 在我的的node.js 防爆preSS服务器。

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

该courtsAmount函数获取调用。但是,在我的客户视图,我没有得到的reuslt。相反,我只是得到一个空的对象。

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.

我认为这是与事实,我的 .query 有所回调,因而做 res.send courtsAmount 实际上是发射之前将一个空的对象。

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?

推荐答案

您courtsAmount不返回任何东西。相反,你应该使用它里面的回调(或承诺),做这样的事情:

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

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

这篇关于为什么我得到一个空的对象,当一个函数在node.js中被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆