CNode

express-modern: 在 express.js 中使用 generator function / async function

分享
Mmagicdawn发布于10 年前最后回复10 年前7 回复6976 浏览0 收藏

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

查看回复

回复 (7)

C
coderfox#1·10 年前

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

来自酷炫的 CNodeMD

M
magicdawn#3·10 年前

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

app.get('/', function(req,res,next){
  co(function* (){
     ...
  }).catch(next)
})
K
klausgao#4·10 年前

我还是习惯直接co

M
magicdawn#5·10 年前
引用 klausgao我还是习惯直接co

@klausgao 里面是 co.wrap

K
Kaijun#6·10 年前

你好 我试了下你的库 使用generator function 或者 await/async 都不能自动传到next… 具体我提了issue, 不知道哪里有问题

M
magicdawn#7·10 年前

自顶。。。

参与回复
登录后即可参与回复。登录