手写 Promise 队列

支持限制并发数

class PromiseQueue {
  limit: number
  active: number
  queue: Array<() => Promise<any>>

  constructor(limit = 3) {
    // 并发限制
    this.limit = limit;
    // 当前活跃数
    this.active = 0;
    // 异步队列
    this.queue = [];
  }

  push(p: () => Promise<any>) {
    this.queue.push(p);
    this.next();
    return this;
  }

  next() {
    if (this.active >= this.limit || !this.queue.length) {
      return;
    }
    this.active++;
    const promiseFac = this.queue.shift();
    if(promiseFac) {
        let promise = promiseFac();
        promise.then((res) => {
            console.log(res)
            this.active--;
            this.next();
        },(error) => {
            console.log(error)
            this.active--;
            this.next();
        })
    }
  }
}

demo 测试地址

posted @ 2022-02-21 15:45  远方的少年🐬  阅读(80)  评论(0编辑  收藏  举报