Nodejs:在异步结果上返回结果

时间:2015-09-17 13:39:34

标签: sql database node.js asynchronous controller

我正在尝试在nodejs中编写一个RESTfull API,它基本上是围绕一个控制器/模型架构,我遇到了一些关于nodejs的异步性质的问题:

Station.js :(控制器)

'use strict';

var url = require('url');

var Stations = require('./StationsService');

module.exports.stationsGet = function stationsGet(req, res, next){

    var result = Stations.stationsGet(req.swagger.params['arg']);

    if(typeof result !== 'undefined') {
        res.setHeader('Content-Type', 'application/json');
        res.end(JSON.stringify(result || {}, null, 2));
    }
    else
        res.end();
};

StationService.js :(模型)

'use strict';
exports.stationsGet = function(param){
    var data_output = {};

    var sql = 'SELECT * FROM foo WHERE args = ${foo}';

    db.execute(sql, {foo: param}, db.queryResult.any, function(result){
        // 'result' containing the query data
    });

    // Ideally: data_output = result;

    return data_output;
}

问题是如果我在我的db.execute上使用回调继续,我必须给所有控制器上下文(res,...)回复客户端,并且它打破了模型/控制器模式,因为我的modele使剩余的控制器工作。

是否有(简单?)方法在stationsGet()中获取查询结果然后返回它? 是否真的违背了nodejs的性质,如果是的话,如何在这种情况下采用正确的行为?

PS:我正在使用swagger生成了nodejs的文件和基础结构。

1 个答案:

答案 0 :(得分:1)

在这种情况下你应该使用回调(看一下promises)

您的控制器将如下所示:

'use strict';

var url = require('url');

var Stations = require('./StationsService');

module.exports.stationsGet = function stationsGet(req, res, next){

    Stations.stationsGet(req.swagger.params['arg'], function(err, result) {
        if(typeof result !== 'undefined') {
            res.setHeader('Content-Type', 'application/json');
            res.end(JSON.stringify(result || {}, null, 2));
        }
        else
            res.end();
    });
};

您制作的模型必须接受回调作为最后一个参数,然后返回errresult,如下所示:

'use strict';
exports.stationsGet = function(param, cb){
    var data_output = {};

    var sql = 'SELECT * FROM foo WHERE args = ${foo}';

    db.execute(sql, {foo: param}, db.queryResult.any, function(result){
       cb(null, result); // first parameter is the error and the second is the result, this is pretty standard in node
    });
}

我希望这有助于你

相关问题