Nodejs:返回异步结果的结果 [英] Nodejs: returning result on async result

查看:304
本文介绍了Nodejs:返回异步结果的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在nodejs中编写一个RESTfull API,基本上是一个控制器/模式模式,我遇到一些关于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'包含查询数据
} ;

//理想情况下:data_output = result;

return data_output;
}

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



有没有一种(easy?)的方法来获取查询的结果在stationsGet()然后返回呢?
是真的反对nodejs性质,如果是这样如何采取正确的行为在这种情况下?



PS:我使用swagger已生成文件和基本结构。

解决方案

在这种情况下你应该使用一个回调/ p>

您的控制器将如下所示:

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

您所创建的模型必须接受回调作为最后一个参数,并返回 err 并且 result 如下所示:

 '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); //第一个参数是错误,第二个是结果,这在节点
}中是相当标准的);
}

我希望这可以帮助你


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.

解决方案

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

这篇关于Nodejs:返回异步结果的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆