我如何使用co with express?

时间:2016-02-12 01:33:41

标签: node.js express co

我正在使用带节点的express,并希望使用co / yield模式来纠缠我的异步回调。

目前的代码如下:

web.post('/request/path', function(req, res, next) {
    co(function *() {
        let body = req.body
        let account = yield db.get('account', {key: body.account})
        if (!account) {
            throw new Error('Cannot find account')
        }
        let host = yield db.get('host', {key: body.hostname})
        ....

    }).catch(err => {log.info(err) ; res.send({error: err})})

这非常有效,但我希望能够简化前两行:

web.post('/request/path', function(req, res, next) {
    co(function *() {

是否有可能以某种方式将co(function *()集成到第一行?express是否支持co()和屈服函数?

2 个答案:

答案 0 :(得分:5)

您可以使用co-express和承诺。

实施例,

router.get('/', wrap(function* (req, res, next) {
    var val;

    try {
        val = yield aPromise();
    } catch (e) {
        return next(e);
    }

    res.send(val);
}));

答案 1 :(得分:1)

您可以使用箭头功能简化语法:

web.post('/request/path', (req, res, next) => co(function *() {
        //...
}).catch(err => {log.info(err) ; res.send({error: err})})

我没有看到使用其他套餐的任何额外好处。当async / await上架时,我们可能会看到express获得更新。

另一方面,制作自己的共同表达非常简单:

考虑'共同表达/ index.js'

module.exports = generator => (req, res, next) => require('co').wrap(generator)(req, res, next).catch(err => res.status(500).send(err));

现在:

var coe = require('./co-express');
web.post('/request/path', coe(function *(req, res, next) {
    //...
})

通过这种方式,您获得了最新的合作套餐。

相关问题