全栈应用开发中并发式请求

 class SlotLimiter {

  constructor(maxConcurrency) {

    this.max = maxConcurrency; // 槽位总数,即允许同时执行的任务数量上限

    this.running = 0; // 当前正在执行的任务数(已占用的槽位数)

    this.queue = []; // 等待队列,存放暂时无法执行的任务的启动函数

  }add(task) {

    return new Promise((resolve, reject) => {

      const runTask = () => {

        this.running++;

        Promise.resolve(task())

          .then(resolve, reject)

          .finally(() => {

            this.running--;

            this.next();

          });

      };


      if (this.running < this.max) {

        runTask();

      } else {

        this.queue.push(runTask);

      }

    });

}

next() {

  if (this.queue.length && this.running < this.max) {

    const nextTask = this.queue.shift();

    nextTask();

  }

}

class DistributedLimiter {

  constructor(options) {

    this.pools = new Map();

    for (const [key, max] of Object.entries(options)) {

      this.pools.set(key, new SlotLimiter(max));

    }

  }

评论

此博客中的热门博文

Oracle Cloud Free Tier: Spinning Up the 2-Core 12GB Ampere A1 Instance

Wise Multi-Currency Account Walkthrough: 40+ Currencies + Local Bank Details

MiMo-V2.5 Goes Offline Tomorrow at 10:00: Your V2.6 Migration Checklist