//Promise并发控制池
import EventEmitter from "events";

class PromisePool extends EventEmitter {
  constructor(concurrent, promiseCreator) {
    super();
    this.concurrent = concurrent || 5;
    this.promiseCreator = promiseCreator;
  }

  start(datas) {
    const self = this;
    let index = 0;
    let running = 0;
    return new Promise((resolved) => {
      const execute = () => {
        running++;
        self.promiseCreator(datas[index++]).finally(() => {
          self.emit("count", index);
          running--;
          if (running < self.concurrent && datas.length > index) {
            execute();
          } else if (datas.length == index && running == 0) {
            resolved();
          }
        });
      };
      while (running < self.concurrent && datas.length > index) {
        execute();
      }
    });
  }
}

export function create(concurrent, promiseCreator) {
  return new PromisePool(concurrent, promiseCreator);
}
