【问题标题】:How can I use co with express?如何将 co 与 express 一起使用?
【发布时间】:2016-05-23 01:19:56
【问题描述】:

我将 express 与 node 一起使用,并希望使用 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})})

这确实很好,但我希望能够简化前 2 行:

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

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

【问题讨论】:

    标签: node.js express co


    【解决方案1】:

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

    例子,

    router.get('/', wrap(function* (req, res, next) {
        var val;
    
        try {
            val = yield aPromise();
        } catch (e) {
            return next(e);
        }
    
        res.send(val);
    }));
    

    【讨论】:

      【解决方案2】:

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

      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) {
          //...
      })
      

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

      【讨论】:

        猜你喜欢
        • 2015-11-03
        • 2016-06-16
        • 2015-09-15
        • 2013-08-16
        • 1970-01-01
        • 1970-01-01
        • 2011-06-01
        • 2012-12-13
        • 2022-01-09
        相关资源
        最近更新 更多