1

在我的 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();
        }
    }));

在我的 question_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 返回,它可以工作。

4

1 回答 1

1

我不知道您正在使用的库,但考虑到您有一个回调作为参数,find可能是一个异步函数。您将不得不相应地更改您的代码:

问题_api.js:

exports.list = function(req, res){
    questions.list_top_rates(req, function(final_result) {
        res.json(final_result);
    });
};

问题.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]);
    });
};
于 2014-02-07T13:51:21.317 回答