怎么手写一个类似koa的洋葱模型

今天模拟写了一下中间件模式
突然想到洋葱模型,没啥思路。。。大神能不能看下我写的代码,帮忙指点指点

class App {

    constructor() {
        this.list = []

        this.ctx = {}
        
        this.next = ()=>{
            this.continue =true;
        }
    }

    use(func) {
        this.list.push(func);
    }

    run() {
        while(this.list.length>0) {

            let func = this.list[0];
            this.continue =false;
            func(this.ctx,this.next);
            this.list.shift();
            if(!this.continue ) {
                this.list = []
            }

        }
    }

}

let app = new App()

app.use((ctx,next)=>{
    ctx.name="111"
    next()
    console.log("最后执行");
})

app.use((ctx,next)=>{
    ctx.age  = 12;
    next()
    console.log("最后执行 -1");
})


app.use((ctx,next)=>{
    console.log("ctx",ctx);
    next()
    console.log("最后执行 -2");
})

app.run()
阅读 1.7k
1 个回答

核心代码:

// 函数集(相当于中间件集合)
let arr = [
  (next) => { console.log('a1'); next(); console.log('a2'); },
  (next) => { console.log('b1'); next(); console.log('b2'); },
  (next) => { console.log('c1'); next(); console.log('c2'); },
];

// 用递归实现洋葱模型
let dispatch = (i) => {
  let fn = arr[i];
  if (typeof fn !== 'function') return
  let next = () => dispatch(i + 1);
  fn(next)
}
dispatch(0)

// 运行结果 ==> a1 > b1 > c1 > c2 > b2 > a1
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题