并行限制处理

40 阅读1分钟

并行限制处理

const LIMIT = 2;

class RequestWithLimit {
  counter = 0;
  queneList = [];
  addRequest(func) {
    return new Promise((res, rej) => {
      this.queneList.push({ func, res, rej });
      this.callRequset();
    });
  }
  callRequset() {
    if (this.queneList.length > 0 && this.counter < LIMIT) {
      const { func, res, rej } = this.queneList.shift();
      this.counter++;
      func()
        .then(res)
        .catch(rej)
        .finally(() => {
          this.counter--;
          this.callRequset();
        });
    }
  }
}

const q1 = new RequestWithLimit();
const func1 = () => {
  return new Promise((res, rej) => {
    setTimeout(() => {
      res("1");
      console.log(111);
    }, 1000);
  });
};
const func2 = () => {
  return new Promise((res, rej) => {
    // console.log("timer2");
    setTimeout(() => {
      res("1");
      console.log(222);
    }, 1000);
  });
};

const func3 = () => {
  return new Promise((res, rej) => {
    // console.log("timer3");
    setTimeout(() => {
      res("1");
      console.log(333);
    }, 1000);
  });
};

const func4 = () => {
  return new Promise((res, rej) => {
    // console.log("timer4");
    setTimeout(() => {
      res("1");
      console.log(444);
    }, 1000);
  });
};

q1.addRequest(func1);
q1.addRequest(func2);
q1.addRequest(func3);
q1.addRequest(func4);

预期先输出两个console 后输出两个