转载

在 Express 中愉快地使用 Generator

express-coroutine

Generator function to be used as middlewares in express like koa. ( use lei-coroutine )

Installation

npm install express-coroutine --save

Usage

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!');
});

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!');
});

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);
};

app.get('/:user', middleware, function* (req, res) {
  res.send('it works!');
});

More detail demo can be found in test.js

原文  https://github.com/yourtion/express-coroutine
正文到此结束
Loading...