在前端开发中,如果需要处理大量的并发请求,可以使用一些技术来控制并发数量,以避免过多的请求对服务器造成压力或导致浏览器性能问题。以下是几种常见的方法:
方法一:使用 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);
});
解释
- 批量处理:
- 将请求分成多个批次,每个批次使用
Promise.all
进行并发处理。
- 将请求分成多个批次,每个批次使用
p-limit
库:- 使用 p-limit 库来限制并发请求数量,更方便地控制并发。
- 自定义并发控制器:
- 编写一个自定义的并发控制器,通过 Promise.race 来控制并发请求数量。