JavaScript 的 中间件模式
等级 5507 次按键
中间件模式链接可以顺序转换数据或控制流程的处理程序。
JavaScript 代码
// 实现中间件模式的Pipeline类1class Pipeline {2 constructor() { // 存储中间件函数的数组3 this.middlewares = [];4 }5 use(fn) { // 将中间件添加到管道6 this.middlewares.push(fn); // 返回this用于链接7 return this;8 }9 async execute(context) { // 跟踪当前中间件索引10 let index = 0; // 创建next函数调用下一个中间件11 const next = async () => { // 如果还有更多中间件,执行它们12 if (index < this.middlewares.length) { // 执行当前中间件并递增index,同时传入next以便继续调用链13 await this.middlewares[index++](context, next);14 }15 }; // 启动中间件链16 await next(); // 返回修改后的上下文17 return context;18 }19}20 // 创建管道实例21const pipeline = new Pipeline();// 添加中间件22pipeline // 第一个中间件设置ctx.a = 1,然后调用next23 .use(async (ctx, next) => { ctx.a = 1; await next(); }) // 第二个中间件设置ctx.b = ctx.a + 1 = 224 .use(async (ctx, next) => { ctx.b = ctx.a + 1; await next(); });25 // 执行并记录结果: { a: 1, b: 2 }26pipeline.execute({}).then(console.log);运行结果
{ a: 1, b: 2 }可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 JavaScript 代码中需要输入的符号及其出现次数。
(× 17)× 17;× 15.× 14{× 9}× 9=× 9,× 3+× 3>× 3