我如何使用快递合作?

Sen*_*eep 3 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})})
Run Code Online (Sandbox Code Playgroud)

这工作得很好,但我希望能够简化前两行:

web.post('/request/path', function(req, res, next) {
    co(function *() {
Run Code Online (Sandbox Code Playgroud)

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

Swa*_*iri 5

您可以与promises一起使用co-express.

例,

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

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

    res.send(val);
}));
Run Code Online (Sandbox Code Playgroud)