class TaskPro { #tasks = []; #isRun = false; #currIndex = 0;
addTask(task) { this.#tasks.push(task); } async run() { if (this.#isRun) return; this.#isRun = true; await this.#runTask(); } async #runTask() { if (this.#runTaskBoundary()) return; const task = this.#tasks[this.#currIndex]; const i = this.#currIndex; await task(this.next.bind(this)); const j = this.#currIndex; if (i === j) { await this.next(); } } #runTaskBoundary() { if (this.#currIndex >= this.#tasks.length) { this.#isRun = false; this.#currIndex = 0; this.#tasks = []; return true; } return false; } async next() { this.#currIndex++; await this.#runTask(); } }
const t = new TaskPro();
t.addTask(async (next) => { console.log("task1 start"); await next(); console.log("task1 end"); });
t.addTask(() => { console.log("task2"); }); t.addTask(() => { console.log("task3"); });
t.run();
|