1. 什么是洋葱模型
洋葱模型,是 koa 中间件的执行顺序,洋葱模型的执行顺序是:
- 中间件 A 开始执行
- 中间件 A 执行完毕,执行下一个中间件 B
- 中间件 B 执行完毕,执行下一个中间件 C
….
2. 实现一个洋葱模型的任务执行构造函数
需求:实现一个构造函数满足以下需求
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| const t = new TaskPro(); t.addTask(async (next) => { console.log("1", "start"); await next(); console.log("1", "end"); }); t.addTask(() => { console.log("2"); }); t.addTask(() => { console.log("3"); });
t.run();
|
实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| class TaskPro { _tasklist = []; _running = false; _currentIndex = 0;
addTask(task) { this._tasklist.push(task); } async run() {
if (this._running) return; this._running = true; this._runTask(); }
async _next() { this._currentIndex++; this._runTask(); } async _runTask() { if (this._currentIndex >= this._tasklist.length) { this._running = false; this._tasklist = []; return; } const prevIndex = this._currentIndex;
const task = this._tasklist[this._currentIndex];
await task(this._next.bind(this)); const nextIndex = this._currentIndex; if (prevIndex === nextIndex) { this._next(); } } }
const t = new TaskPro(); t.addTask(async (next) => { console.log("1", "start"); await next(); console.log("1", "end"); }); t.addTask(() => { console.log("2"); }); t.addTask(() => { console.log("3"); }); t.run();
|