# 任务池

class TaskPool {
  maxTaskLength = 2
  pool = []
  waitQuene = []
  addTask(task) {
    const obj = {
      task,
      reslove : () => {},
    }
    if (this.pool.length >= this.maxTaskLength) {
      this.waitQuene.push(obj);
    } else {
      this.pool.push(obj);
    }
    const result =  new Promise((reslove, reject) => {
      obj.reslove = reslove;
      this.runTask(obj)
    });
    return result;
  }

  runTask(obj) {
    const {task, reslove} = obj;
    const index = this.pool.indexOf(obj);
    if (index > -1) {
      task().then((data) => {
        reslove(data);
        this.pool.splice(index, 1);
        const append = this.waitQuene.splice(0, 1);
        if (append.length === 1) {
          const willRunObj = append[0];
          this.pool.push(willRunObj);
          this.runTask(willRunObj);
        }
      });
    }
  }
}

const mTaskPool = new TaskPool();
mTaskPool.addTask(() => {
  return new Promise(( reslove, reject) => { console.log(' run task 1'); setTimeout(() => reslove('task 1'), 2000) });
}).then((data) => {
  console.log(data)
});
mTaskPool.addTask(() => {
  return new Promise(( reslove, reject) => { console.log(' run task 2'); setTimeout(() => reslove('task 2'), 2000) });
}).then((data) => {
  console.log(data)
});
mTaskPool.addTask(() => {
  return new Promise(( reslove, reject) => { console.log(' run task 3'); setTimeout(() => reslove('task 3'), 2000) });
}).then((data) => {
  console.log(data)
});