假如有几十个请求如何控制并发

在前端开发中,如果需要处理大量的并发请求,可以使用一些技术来控制并发数量,以避免过多的请求对服务器造成压力或导致浏览器性能问题。以下是几种常见的方法:

方法一:使用 Promise.all 和批量处理

将请求分成多个批次,每个批次使用 Promise.all 进行并发处理。

const fetchData = async (urls) => {
  const batchSize = 5; // 每批次请求数量
  const results = [];

  for (let i = 0; i < urls.length; i += batchSize) {
    const batch = urls.slice(i, i + batchSize);
    const batchResults = await Promise.all(batch.map(url => fetch(url).then(res => res.json())));
    results.push(...batchResults);
  }

  return results;
};

// 示例
const urls = [
  'https://api.example.com/data1',
  'https://api.example.com/data2',
  // ... 其他 URL
];

fetchData(urls).then(results => {
  console.log(results);
});

方法二:使用 p-limit

p-limit 是一个用于限制并发数的库,可以更方便地控制并发请求数量。

安装 p-limit

npm install p-limit

使用 p-limit

import pLimit from 'p-limit';

const limit = pLimit(5); // 设置并发限制为 5

const fetchData = async (urls) => {
  const promises = urls.map(url => limit(() => fetch(url).then(res => res.json())));
  const results = await Promise.all(promises);
  return results;
};

// 示例
const urls = [
  'https://api.example.com/data1',
  'https://api.example.com/data2',
  // ... 其他 URL
];

fetchData(urls).then(results => {
  console.log(results);
});

方法三:使用自定义并发控制器

你也可以编写一个自定义的并发控制器来限制并发请求数量。

const fetchWithConcurrency = async (urls, maxConcurrency) => {
  const results = [];
  const executing = [];

  for (const url of urls) {
    const promise = fetch(url).then(res => res.json());
    results.push(promise);

    if (maxConcurrency <= urls.length) {
      const e = promise.then(() => executing.splice(executing.indexOf(e), 1));
      executing.push(e);
      if (executing.length >= maxConcurrency) {
        await Promise.race(executing);
      }
    }
  }

  return Promise.all(results);
};

// 示例
const urls = [
  'https://api.example.com/data1',
  'https://api.example.com/data2',
  // ... 其他 URL
];

fetchWithConcurrency(urls, 5).then(results => {
  console.log(results);
});

解释

  1. 批量处理:
    • 将请求分成多个批次,每个批次使用 Promise.all 进行并发处理。
  2. p-limit:
    • 使用 p-limit 库来限制并发请求数量,更方便地控制并发。
  3. 自定义并发控制器:
    • 编写一个自定义的并发控制器,通过 Promise.race 来控制并发请求数量。

通过这些方法,你可以有效地控制并发请求数量,避免过多的请求对服务器造成压力或导致浏览器性能问题。选择合适的方法取决于你的具体需求和项目情况。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值