class TaskPro {
#tasks = [];
#isRun = false;
#currIndex = 0;
/**
* 添加任务
* @param {Function} task
*/
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];
//记录当前下标用于判定是否调用next
const i = this.#currIndex;
// 注入next
await task(this.next.bind(this));
const j = this.#currIndex;
//如果没调next 则需要手动调用
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(); //输出 task1 start task2 task3 task1 end