Nodejs: returning result on async result

我怕爱的太早我们不能终老 提交于 2019-12-04 05:59:32

问题


I'm trying to code an RESTfull API in nodejs which is basically around a controller/modele schema and I meet some problems about the async nature of nodejs:

Station.js: (controller)

'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: (modele)

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

The problem is if I use callback on my db.execute to continue, I have to give all the controller context (res, ...) to reply back to the client, and it break the modele/controller schema since my modele does the remaining controller work.

Is there a (easy?) way to get the result of the query in stationsGet() and then returning it? Is it really against the nodejs nature and if so how to adopt the correct behavior in that case?

PS: I'm using swagger which has generated the files and base structure for nodejs.


回答1:


You should use a callback in this case (take a look at promises as well)

your controller will look like this:

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

And the model you made must accept a callback as a last parameter, and you return err and the result like follows:

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

I hope this helps you



来源:https://stackoverflow.com/questions/32631790/nodejs-returning-result-on-async-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!