js如何实现并发请求
使用 Promise.all 实现并发请求
Promise.all 可以并行执行多个异步请求,并在所有请求完成后统一处理结果。传入一个包含多个 Promise 的数组,返回一个新的 Promise,当所有请求都成功时才会 resolve。
const request1 = fetch('https://api.example.com/data1');
const request2 = fetch('https://api.example.com/data2');
const request3 = fetch('https://api.example.com/data3');
Promise.all([request1, request2, request3])
.then(responses => {
// 所有请求完成后的处理
console.log(responses);
})
.catch(error => {
// 任一请求失败的处理
console.error(error);
});
使用 Promise.allSettled 处理可能失败的请求
与 Promise.all 不同,Promise.allSettled 会等待所有 Promise 完成,无论成功或失败。返回一个数组,包含每个 Promise 的状态和结果。
const requests = [
fetch('https://api.example.com/data1'),
fetch('https://api.example.com/data2'),
fetch('https://api.example.com/data3')
];
Promise.allSettled(requests)
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('成功:', result.value);
} else {
console.log('失败:', result.reason);
}
});
});
使用 async/await 结合并发请求
async/await 可以与 Promise.all 结合使用,使代码更简洁易读。
async function fetchConcurrently() {
try {
const [response1, response2] = await Promise.all([
fetch('https://api.example.com/data1'),
fetch('https://api.example.com/data2')
]);
const data1 = await response1.json();
const data2 = await response2.json();
console.log(data1, data2);
} catch (error) {
console.error(error);
}
}
fetchConcurrently();
限制并发数量的实现
当需要控制并发请求数量时,可以使用第三方库如 p-limit,或者手动实现并发控制。
async function limitedConcurrency(urls, limit) {
const results = [];
const executing = [];
for (const url of urls) {
const p = fetch(url).then(res => {
executing.splice(executing.indexOf(p), 1);
return res.json();
});
executing.push(p);
results.push(p);
if (executing.length >= limit) {
await Promise.race(executing);
}
}
return Promise.all(results);
}
limitedConcurrency(['url1', 'url2', 'url3'], 2)
.then(data => console.log(data));
使用 Axios 实现并发请求
如果使用 Axios 库,并发请求的实现方式类似。
const axios = require('axios');
const request1 = axios.get('https://api.example.com/data1');
const request2 = axios.get('https://api.example.com/data2');
Promise.all([request1, request2])
.then(responses => {
console.log(responses[0].data, responses[1].data);
})
.catch(error => {
console.error(error);
});
以上方法涵盖了 JavaScript 中实现并发请求的主要场景,根据具体需求选择合适的方式。







