Nodejs: returning result on async result

前端 未结 1 737
走了就别回头了
走了就别回头了 2021-01-27 17:20

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:

1条回答
  •  借酒劲吻你
    2021-01-27 17:56

    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

    0 讨论(0)
提交回复
热议问题