generator天然适配洋葱模型,通过yield*实现中间件嵌套调用;核心是构建可注册、编排、中断的调度器,支持上下文透传与插件化集成。

Generator 可以通过 yield 暂停执行、交出控制权,天然适配中间件“洋葱模型”的嵌套调用逻辑,在插件化架构中实现可插拔的中间件流。关键不在于 Generator 本身,而在于用它构建一个可注册、可编排、可中断的执行调度器。
用 Generator 封装中间件链,形成可组合的执行单元
每个中间件写成接受 next(即下一个中间件的 Generator 函数)并返回 Generator 的函数。调用时通过 yield* next() 将控制权向下传递,形成嵌套调用栈:
const logger = (next) => function* () {
console.log('→ before');
yield* next();
console.log('← after');
};
<p>const auth = (next) => function<em> () {
console.log('→ check auth');
yield</em> next();
console.log('← auth done');
};</p>这样每个中间件都保持独立,不耦合具体执行顺序,只关心“执行前/后”和“是否继续”。
构建插件注册与执行调度器
定义一个核心调度器(如 MiddlewareRunner),支持动态添加中间件,并最终生成一个顶层 Generator 函数:
class MiddlewareRunner {
constructor() {
this.middlewares = [];
}
<p>use(mw) {
this.middlewares.push(mw);
return this; // 支持链式调用
}</p><p>compose() {
const stack = this.middlewares;
if (stack.length === 0) return function* () {};</p><pre class="brush:php;toolbar:false;">return function* (ctx) {
function createNext(index) {
return index >= stack.length
? function* () {} // 终止函数
: function* () {
yield* stack[index](createNext(index + 1))(ctx);
};
}
yield* createNext(0)(ctx);
};} }
使用方式简洁:
const runner = new MiddlewareRunner();
runner.use(logger).use(auth).use((next) => function* () {
console.log('→ handler');
yield 'done';
});
<p>const main = runner.compose();
for (const val of main({})) {
console.log('yielded:', val); // → before → check auth → handler ← auth done ← before
}</p>支持插件级中断与上下文透传
中间件可通过 ctx 对象共享状态,并约定中断协议(例如设置 ctx.skip = true 或抛出特定错误)。在调度器中检查中断信号,跳过后续中间件:
- 每个中间件接收统一
ctx,可读写任意字段(如ctx.user,ctx.status) - 在
createNext中插入判断:if (ctx.skip) return; - 也可让中间件
throw new SkipError(),由外层try/catch捕获并终止流程
与现代插件系统集成(如微前端或 CLI 工具)
Generator 中间件可作为插件导出的标准接口:
- 插件包默认导出一个中间件工厂函数:
export default (options) => (next) => function* () { ... } - 主系统扫描插件目录,按优先级或配置顺序
.use(plugin(options)) - 支持热插拔:运行时修改
runner.middlewares并重新compose()(注意避免正在迭代的 Generator 实例)
这种方式既保留了 Generator 的可控暂停能力,又把流程编排权交给插件系统,真正实现“行为可插拔、顺序可配置、执行可干预”。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











