手写算法模拟KOA
js
// 实现 洋葱模型类 App,打印a,b,c,C,B,A
class App {
constructor() {
this.tasks = []
this.ctx = null
}
use(fn) {
this.tasks.push(fn)
}
async run() {
const ctx = this.ctx
async function loop(tasks) {
const fn = tasks.shift()
if (fn) {
await fn(ctx, () => {
loop(tasks)
})
}
}
loop(this.tasks)
}
}
// 测试
const app = new App();
app.use((_, next) => {
console.log("a");
next();
console.log("A");
});
app.use((_, next) => {
console.log("b");
next();
console.log("B");
});
app.use((_, next) => {
console.log("c");
next();
console.log("C");
});
app.run();