在nodejs中使用asynchronous库
你好,这里是我的代码:
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实现asynchronous库(caolan),并将findOne()与send_result结合起来,因为它看起来相当混乱。
编辑1 :
我用这个策略,但是我不确定是否正确,有什么build议?
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(); });
}
任何build议?
对于他们在Express.js中所称的路由,实际上几乎不需要使用asynchronous库。 原因在于路线实际上是一种控制,使它们自我stream动。 他们采取尽可能多的中间件,所以你可以将你的路线分成小块的代码。
例如,假设你想从一个数据库中获得一个logging/文档,然后把它作为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 );
如果你为这样的路由编写中间件,那么你最终将得到一个小的构build块,你可以在整个应用程序中轻松地重用。
- 如何使用expressjs和mongodb使用promises /callback?
- node.jsasynchronous串行函数的参数
- NodeJS,asynchronousforEachSeries执行顺序
- 我可以在async.js forEach中扩展迭代器的function吗?
- 有关node.js中的async.waterfall的问题
- 如何在async.js迭代器(节点)中添加延迟
- Nodejsasynchronous编程 – 为什么需要“asynchronous”模块? 什么是“回拨地狱”/“厄运金字塔”?
- asynchronous:使用Async.forEach组合两个mongodb集合
- asynchronous队列,文件stream结束时如何知道两者何时完成