Skip to content

任务执行的洋葱模型

Code

ts
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 'start', 2, 3, 1 'end'

实现

ts
class TaskPro {
  #taskList = [];
  #isRunning = false;
  #currentIndex = 0;
  addTask(task) {
    this.#taskList.push(task);
  },
  run() {
    // 当前任务正在执行
    if (this.#isRunning) {
      return;
    }
    this.#isRunning = true;
    await this.#runTask();
  }

  async #runTask() {
    if (this.#currentIndex >= this.#taskList.length) {
      this.#isRunning = false;
      this.#currentIndex = 0;
      this.#taskList = [];
      return;
    }
    const i = this.#currentIndex;
    const task = this.#taskList[this.#currentIndex];
    const j = this.#currentIndex;
    await task(this.#next.bind(this));
    if (i === j) {
      await this.#next();
    }
  }

  async #next() {
    this.#currentIndex ++;
    await this.#runTask();
  }

}