js实现并发量控制
并发量控制的实现方法
在JavaScript中实现并发量控制的核心思路是通过队列管理任务,限制同时执行的任务数量。以下是几种常见方法:
Promise队列与并发控制
利用Promise和队列机制控制并发:

class ConcurrencyControl {
constructor(maxConcurrent) {
this.maxConcurrent = maxConcurrent;
this.queue = [];
this.running = 0;
}
add(task) {
return new Promise((resolve, reject) => {
this.queue.push({ task, resolve, reject });
this.run();
});
}
run() {
while (this.queue.length > 0 && this.running < this.maxConcurrent) {
const { task, resolve, reject } = this.queue.shift();
this.running++;
Promise.resolve(task())
.then(resolve)
.catch(reject)
.finally(() => {
this.running--;
this.run();
});
}
}
}
使用方法:
const controller = new ConcurrencyControl(3);
// 添加任务
controller.add(() => fetch('/api1')).then(console.log);
controller.add(() => fetch('/api2')).then(console.log);
async/await实现
通过async函数和队列管理:

async function parallelLimit(tasks, limit) {
const results = [];
const executing = new Set();
for (const task of tasks) {
const p = task().then(res => {
executing.delete(p);
return res;
});
executing.add(p);
results.push(p);
if (executing.size >= limit) {
await Promise.race(executing);
}
}
return Promise.all(results);
}
使用方法:
const tasks = [/* 多个返回Promise的函数 */];
parallelLimit(tasks, 2).then(console.log);
使用第三方库
现有库如p-limit可直接使用:
import pLimit from 'p-limit';
const limit = pLimit(2); // 并发数为2
const tasks = [
limit(() => fetch('/api1')),
limit(() => fetch('/api2'))
];
Promise.all(tasks).then(console.log);
注意事项
- 错误处理需在任务内部或调用处捕获
- 任务完成后需及时释放并发槽位
- 浏览器环境需考虑请求取消(AbortController)
- Node.js环境可结合
worker_threads实现真正并行
以上方法可根据实际场景选择,核心思想均为通过队列和Promise状态管理控制并发流程。





