JS实现并发请求
使用 Promise.all 实现并发请求
Promise.all 方法可以接收一个 Promise 数组作为参数,并返回一个新的 Promise。当所有传入的 Promise 都成功完成时,返回的 Promise 才会成功完成,结果是一个包含所有 Promise 结果的数组。
const urls = ['url1', 'url2', 'url3'];
const requests = urls.map(url => fetch(url));
Promise.all(requests)
.then(responses => Promise.all(responses.map(res => res.json())))
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
使用 Promise.allSettled 处理部分失败
Promise.allSettled 方法会在所有给定的 Promise 都完成(无论是成功还是失败)后返回结果,适合需要处理部分请求失败的情况。
const urls = ['url1', 'url2', 'url3'];
const requests = urls.map(url => fetch(url).catch(e => e));
Promise.allSettled(requests)
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Success:', result.value);
} else {
console.log('Error:', result.reason);
}
});
});
使用 async/await 语法简化代码
async/await 语法可以让并发请求的代码更加清晰易读。
async function fetchAll(urls) {
try {
const responses = await Promise.all(urls.map(url => fetch(url)));
const data = await Promise.all(responses.map(res => res.json()));
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
fetchAll(['url1', 'url2', 'url3']);
限制并发数量的实现
当需要控制并发请求的数量时,可以使用以下方法。
async function limitedConcurrency(urls, limit) {
const results = [];
const executing = new Set();
for (const url of urls) {
const promise = fetch(url).then(res => res.json());
results.push(promise);
executing.add(promise);
promise.finally(() => executing.delete(promise));
if (executing.size >= limit) {
await Promise.race(executing);
}
}
return Promise.all(results);
}
limitedConcurrency(['url1', 'url2', 'url3'], 2)
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
使用第三方库实现并发控制
一些第三方库如 p-limit 可以更方便地实现并发控制。

import pLimit from 'p-limit';
const limit = pLimit(2); // 并发限制为2
const urls = ['url1', 'url2', 'url3'];
const run = async () => {
const results = await Promise.all(
urls.map(url => limit(() => fetch(url).then(res => res.json())))
);
console.log(results);
};
run().catch(console.error);






