【代码练习】javaScript任务执行的洋葱模型

我们要实现如下的一个 TaskPro 的类,它允许用户添加一系列的任务,并按照添加的顺序依次执行这些任务。用户可以手动调用next执行下一个任务,如果没有调用next,实现的类中需要主动调用下一个任务进行执行。

根据如下代码,需要实现TaskPro类:

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

实现的TaskPro类如下:

class TaskPro {
  constructor() {
    this._taskList = [];
    this._isRunning = false;
    this._currentIndex = 0;
    this._next = async () => {
      this._currentIndex++;
      await this._runTask();
    };
  }
  addTask(task) {
    this._taskList.push(task);
  }

  run() {
    // 如果正在运行或者没有任务,则直接返回
    if (this._isRunning || !this._taskList.length) {
      return;
    }
    this._isRunning = true;
    this._runTask();
  }

  /**
   * 取出一个任务执行
   *
   */
  async _runTask() {
    if (this._currentIndex >= this._taskList.length) {
      this._reset();
      return;
    }
    const i = this._currentIndex;
    const task = this._taskList[this._currentIndex];
    await task(this._next);
    const j = this._currentIndex;
    if (i === j) {
      await this._next();
    }
  }

  _reset() {
    this._taskList = [];
    this._isRunning = false;
    this._currentIndex = 0;
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值