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,然后调用next
23 .use(async (ctx, next) => { ctx.a = 1; await next(); })
// 第二个中间件设置ctx.b = ctx.a + 1 = 2
24 .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

JavaScript 等级 5 的更多代码示例

← 返回 JavaScript 打字练习