【问题标题】:Use Async lib in nodejs在 nodejs 中使用异步库
【发布时间】:2013-08-04 20:05:34
【问题描述】:

大家好,这是我的代码:

function get_group(req, res, next) {
var send_result = function(err, group_list) {
[...]
    res.send(group_list);
    return next();
};

Group.findOne({'_id': req.params._id}, send_result);

}

现在我如何使用 async.series 实现异步库 (caolan) 并将 findOne() 与 send_result 结合起来,代码在我看来非常杂乱无章。

EDIT1

我使用了这个策略,但我不确定是否正确,有什么建议吗?

function get_group(req, res, next) {
async.waterfall([
    function(callback) {
        Group.findOne({'_id': req.params._id}, callback);
    }
],
function (err, group_list){
    res.send(group_list);
    return next();
});

}

有什么建议吗?

【问题讨论】:

  • 应该是和 async.waterfall 相关的东西,但我还是没有成功
  • 我想把函数 send_result 放在外面,这样我就可以在其他地方重复使用它
  • 我刚刚注意到你没有用 express 标签标记这个问题。如果您不使用 express,请这样说,因为我的回答是基于该假设。
  • 这个问题很开放。你的回答对我来说很神奇,我正在尝试用你的回答解决我的问题

标签: node.js async.js


【解决方案1】:

对于他们在 Express.js 中所谓的路由,您实际上几乎不需要使用异步库。原因是路由实际上是它们自己的一种控制流。它们采用任意数量的中间件,因此您可以将路由划分为小代码块。

例如,假设您想从数据库中获取一条记录/文档,然后对其进行处理,然后将其作为 json 发送。然后您可以执行以下操作:

var getOne = function(req, res, next){
    db.one( 'some id', function(err, data){
        if (err){
            return next( { type: 'database', error: err } );
        };

        res.local( 'product', data );
        next();
    });
};

var transformProduct = function(req, res, next){
    var product = res.locals().product;

    transform( product, function(data){
        res.local('product', data);
        next();
    });
};

var sendProduct = function(req, res, next){
    var product = res.locals().product;
    res.json(product);
};

app.get( '/product', getOne, transformProduct, sendProduct );

如果您像这样为路由编写中间件,您最终会得到可以在整个应用程序中轻松重用的小型构建块。

【讨论】:

  • 关于 restify(基于 express)locals() 不起作用,你有什么解决方案吗?
  • 如果您的问题与原始问题没有直接关系,您应该创建一个新问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-21
  • 2014-08-05
  • 2017-02-12
  • 2016-12-14
  • 2019-10-21
  • 2017-05-24
  • 2020-07-11
相关资源
最近更新 更多