Koa 在没有 async/await 时如何实现洋葱模型

使用 Generator 函数实现 Koa 的洋葱模型中间件机制

问题

在没有 async/await 的时候,Koa 是怎么实现洋葱模型的?

解答

洋葱模型是一种中间件设计模式,请求按顺序经过一系列中间件,响应时再按相反顺序返回。在没有 async/await 的情况下,Koa 使用 ES6 的 Generator 函数来实现这一模式。

每个中间件都是一个 Generator 函数,接收两个参数:ctxnextctx 是请求上下文对象,包含请求的所有信息;next 是指向下一个中间件的函数,调用它将控制权传递给下一个中间件。

const Koa = require('koa');
const app = new Koa();

app.use(function *(next) {
  console.log('1. Enter middleware 1');
  yield next;
  console.log('5. Exit middleware 1');
});

app.use(function *(next) {
  console.log('2. Enter middleware 2');
  yield next;
  console.log('4. Exit middleware 2');
});

app.use(function *(next) {
  console.log('3. Enter middleware 3');
  this.body = 'Hello, world!';
});

app.listen(3000);
console.log('Server hil2s on http://localhost:3000');

执行顺序为:1 → 2 → 3 → 4 → 5,完美体现了洋葱模型的特点。通过 yield next 实现中间件的顺序调用,先进后出。

关键点

  • 使用 function* 定义 Generator 函数作为中间件
  • 通过 yield next 将控制权传递给下一个中间件
  • 依赖 co 库来执行 Generator 函数
  • 中间件按洋葱模型顺序执行:先进后出