侧边栏壁纸
  • 累计撰写 47 篇文章
  • 累计创建 2 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

如何限制并发请求数?

利用队列机制控制并发数,当同时发起的请求数达到上限时,新的请求会进入队列等待,直到有空闲位置再执行。定义三个变量:请求队列、最大并发数、正在处理请求数。

代码实现
class RequestQueue {
  constructor(maxConcurrent) {
    this.maxConcurrent = maxConcurrent; // 最大并发数
    this.queue = []; // 请求队列
    this.activeCount = 0; // 正在处理的请求数
  }

  // 添加请求到队列
  add(requestFn) {
    return new Promise((resolve, reject) => {
      const task = () => {
        this.activeCount++;
        requestFn()
          .then(resolve)
          .catch(reject)
          .finally(() => {
            this.activeCount--;
            this.next(); // 一个请求完成后,尝试执行下一个
          });
      };

      // 如果未达并发上限,立即执行;否则入队等待
      if (this.activeCount < this.maxConcurrent) {
        task();
      } else {
        this.queue.push(task);
      }
    });
  }

  // 执行队列中的下一个任务
  next() {
    if (this.queue.length > 0 && this.activeCount < this.maxConcurrent) {
      const nextTask = this.queue.shift();
      nextTask();
    }
  }
}
// 使用示例
const queue = new RequestQueue(3); // 限制最多同时3个请求

// 模拟异步请求函数
const mockRequest = (id, delay) => () => 
  new Promise(resolve => setTimeout(() => resolve(`请求 ${id} 完成`), delay));

// 添加10个请求到队列
for (let i = 0; i < 10; i++) {
  queue.add(mockRequest(i, 1000)).then(result => console.log(result));
}

应用场景
  1. 批量操作

  2. 文件分片上传

  3. 根据网络状况(网络状态 navigator.connection.effectiveType、请求响应时间)或服务器负载(心跳请求)动态调整并发数

第三方库
  1. p-limit
  2. promise-pool
0

评论区