【问题标题】:Nodejs: returning result on async resultNodejs:在异步结果上返回结果
【发布时间】:2015-09-17 22:30:19
【问题描述】:

我正在尝试在 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 让剩下的控制器工作。

有没有一种(简单的?)方法可以在stationGet() 中获取查询结果然后返回它? 这真的违背了 nodejs 的本质吗?如果是,在这种情况下如何采取正确的行为?

PS:我使用的是 swagger,它为 nodejs 生成了文件和基本结构。

【问题讨论】:

    标签: sql database node.js asynchronous controller


    【解决方案1】:

    在这种情况下,您应该使用回调(也请查看 Promise)

    您的控制器将如下所示:

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

    希望对你有帮助

    【讨论】:

    • 感谢您的提示!我会更仔细地研究这个并看看 promise ;)
    猜你喜欢
    • 2014-10-02
    • 2016-03-11
    • 1970-01-01
    • 2018-05-26
    • 1970-01-01
    • 2014-07-20
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多