在nodejs中使用Async lib

时间:2012-05-28 17:34:11

标签: node.js async.js

大家好,我的代码是:

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

}

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

对于他们在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 );

如果你为这样的路线编写中间件,你最终会得到一些小的构建块,你可以在整个应用程序中轻松重复使用。