Koa 中间件 API 极简实现
很久前接触 Koa 的时候,觉得注册中间件( app.use )的 API 很有意思。最近面试时看到别人简历上提到 Koa,就随手出了面试题:Koa 中间件 API 实现。
面试结束后,我自己随手写了实现:
const app = { _middlewares: [], use(fn) { this._middlewares.push(fn) }, run() { const next = (i) => { if (i >= this._middlewares.length) return this._middlewares[i](next.bind(null, i + 1)) } this._middlewares[0](next.bind(null, 1)) }, } app.use((next) => { console.log(1) next() console.log(2) }) app.use((next) => { console.log(3) next() console.log(4) }) app.run() // log => 1 3 4 2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论