express-modern: 在 express.js 中使用 generator function / async function
express-modern
https://github.com/magicdawn/express-modern
- 这个在strongloop自己的博文里的就是这个 https://strongloop.com/strongblog/async-error-handling-expressjs-es7-promises-generators/
- 还有一个包,https://github.com/Greenfields/express-async-wrap, express-async-wrap 只支持 async function. 当然你可以说 co.wrap(gen) 与 async function一样的啊~但是还是有点不一样的。co.wrap得到的function的形参个数是0的,对于express-handler来说,要判断是三个参数还是四个参数来决定是否去传err
于是就有了这个。
分割线,下面是README
express-modern
use async function or generator function with express
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
License
the MIT License http://magicdawn.mit-license.org