express-modern: 在 express.js 中使用 generator function / async function
发布于 9 天前 作者 magicdawn 247 次浏览 最后一次编辑是 7 天前 来自 分享

express-modern

https://github.com/magicdawn/express-modern

于是就有了这个。


分割线,下面是README

express-modern

use async function or generator function with express

Build Status Coverage Status npm version npm downloads npm license

Install

npm i express-modern --save

API

const modern = require('express-modern');

generator function

const app = express();
app.get('/', modern(function * (req, res, next) {
  yield new Promise(r => setTimeout(r, 10));
  res.send('generator function');
}));

const res = yield request(app)
  .get('/')
  .endAsync();
res.text.should.match(/generator/);

the generator function will be wrap via co.wrap. and the modern function will take care of the arity of the handler. see http://expressjs.com/en/guide/error-handling.html

async function

const app = express();
app.get('/', modern(async function(req, res, next) {
  await new Promise(r => setTimeout(r, 10));
  res.send('async function');
}));

const res = yield request(app)
  .get('/')
  .endAsync();
res.text.should.match(/async/);

the async function will be called & the rejected value will be passed to next automatically

normal function

const app = express();
app.get('/', modern((req, res, next) => {
  res.send('normal function');
}));

const res = yield request(app)
  .get('/')
  .endAsync();

res.text.should.match(/normal/);

the modern function does nothing on normal function.

Changelog

CHANGELOG.md

License

the MIT License http://magicdawn.mit-license.org

6 回复

不错啊, 不知道有没有 Definition 文件

来自酷炫的 CNodeMD

@coderfox 这个目前还没有~

这个就是简单的包一层,让你的 generator function 抛出的错误自动的调用 next(err), 要不然,你得这样写

app.get('/', function(req,res,next){
  co(function* (){
     ...
  }).catch(next)
})

我还是习惯直接co

回到顶部