3

我在 node 上使用 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() 和 yielding 函数的支持?

4

2 回答 2

5

您可以将co-express与 Promise 一起使用。

例子,

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

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

    res.send(val);
}));
于 2016-02-12T03:03:13.580 回答
1

您可以使用箭头函数简化语法:

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

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

附带说明一下,制作自己的共同表达非常简单:

考虑'co-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) {
    //...
})

这样你就得到了最新的 co 包。

于 2016-04-10T17:18:52.903 回答