Generator function and Async function to be used as middlewares in express like koa. ( use lei-coroutine )
npm install express-coroutine --save
const express = require('express-coroutine')(require('express'));
const app = express();
const express = require('express-coroutine')(require('express'));
const app = express();
const router = new express.Router();
app.use(router);
router.get('/', function* (req, res) {
res.send('it works!');
});
// also async function
router.get('/', async function (req, res) {
res.send('it works!');
});
Write your express routes by using generator functions as middlewares.
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!');
});
// also async function
app.get('/user2/:id', async function* (req, res) {
const user = await User.findById(req.params.id);
res.send(user);
});
app.listen(8000);
You can also define multiple generator functions just the express way.
const fn = function (req, res, next) {
return new Promise((resolve, reject) => {
if (req.params.user !== 'a') return reject(new Error('Bang!'));
resolve('a');
});
};
const middleware = function* (req, res, next) {
yield fn(req, res, next);
};
const middleware2 = async function (req, res, next) {
await fn(req, res, next);
next();
};
app.get('/:user', middleware, function* (req, res) {
res.send('it works!');
});
app.get('/:user', middleware2, async function (req, res) {
res.send('it works!');
});
More detail demo can be found in test.js
const coroutine = require('express-coroutine').coroutine;