在我的app.js
中question = require('./routes/question_api'),
app.use(orm.express("mysql://root@127.0.0.1/daat", {
define: function (db, models, next) {
var question_model = db.define('questions', {
id : Number,
..... more definitions
}
});
models.question = question_model;
next();
}
}));
在我的问题_api.js
中var questions = require('../lib/questions/questions.js');
//NEW Question
//Get Question by ID
//Get Question By Category
exports.list = function(req, res){
res.json(questions.list_top_rates(req, res));
};
在我的questions.js
中exports.list_top_rates = function(req, res) {
var limit = req.limit || 20;
var final_result = {"1": {}};
//Z means descending
req.models.question.find({}, limit, ["rating", "Z"], function(err, questions) {
final_result = questions;
return final_result[0];
});
return final_result;
// return final_result;
// return {
// 1: "first question , limit is " + limit,
// 2: "second question",
// 3: "third question",
// 4: "forth question"
// }
};
我得到空的结果。如果我直接从question_api.js返回,它就可以了。
答案 0 :(得分:1)
我不知道你正在使用的库,但考虑到你给了一个回调作为参数,find
可能是一个异步函数。您必须相应地更改代码:
question_api.js:
exports.list = function(req, res){
questions.list_top_rates(req, function(final_result) {
res.json(final_result);
});
};
questions.js:
exports.list_top_rates = function(req, callback /* the parameter res is not needed anymore */) {
var limit = req.limit || 20;
var final_result = {"1": {}};
//Z means descending
req.models.question.find({}, limit, ["rating", "Z"], function(err, questions) {
final_result = questions;
callback(final_result[0]);
});
};