请实现这个App类

const app = new App();

app.use(next => setTimeout(() => next(), 500));

app.use(next => {
    console.log(123);
    next();
});
app.run();
// => 500ms之后打印出123
阅读 1.6k
2 个回答
class App {
  private handlers = []
  private current = 0

  next = () => {
    if (this.current < this.handlers.length) {
      this.handlers[this.current++](this.next)
    }
  }

  use(func) {
    this.handlers.push(func)
  }

  run() {
    this.next()
  }
}

const app = new App()
app.use((next) => setTimeout(() => next(), 3 * 1000))

app.use((next) => {
  console.log(123)
  next()
})
app.run()

中间件,搜搜 express 和 koa 中间件

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