为什么在 node.js 中调用函数时会得到一个空对象? [英] Why do I get an empty object when a function is invoked in node.js?
问题描述
我的 node.js
Express Server 中有这个 app.get
.
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());
});
正在调用这个函数:
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;
});
};
正在调用 CourtesAmount 函数.但在我的客户看来,我没有得到 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?
推荐答案
您的 CourtesAmount 不返回任何内容.相反,您应该在其中使用回调(或承诺)来执行以下操作:
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屋!