在 Express 中像 Koa 那样使用 Generator 方法。
安装:
npm install express-coroutine --save
初始化:
// Init express const express = require('express-coroutine')(require('express')); const app = express(); // Init router const express = require('express-coroutine')(require('express')); const app = express(); const router = new expressGenerators.Router(); app.use(router); router.get('/', function* (req, res) { res.send('it works!'); });
使用:
const express = require('express-coroutine')(require('express')); const app = express(); app.get('/user/:id', function* (req, res) { const user = yield User.findById(req.params.id); res.send(user); }) app.get('/error', function* (req, res) { throw new Error('Bang!'); }); app.listen(8000);
更多用法详见测试文件:https://github.com/yourtion/express-coroutine/blob/master/test.js