js 实现一个并发队列
实现并发队列的基本思路
在JavaScript中实现并发队列通常需要控制同时执行的异步任务数量。可以使用Promise和队列管理机制来实现这一功能。
定义并发队列类
创建一个ConcurrentQueue类,包含任务队列和并发控制逻辑。
class ConcurrentQueue {
constructor(concurrency) {
this.concurrency = concurrency;
this.running = 0;
this.queue = [];
}
add(task) {
this.queue.push(task);
this.next();
}
next() {
while (this.running < this.concurrency && this.queue.length) {
const task = this.queue.shift();
task().finally(() => {
this.running--;
this.next();
});
this.running++;
}
}
}
使用示例
创建并发队列实例并添加任务。
const queue = new ConcurrentQueue(2); // 并发数为2
// 模拟异步任务
function asyncTask(id, delay) {
return () => new Promise(resolve => {
console.log(`Task ${id} started`);
setTimeout(() => {
console.log(`Task ${id} completed`);
resolve();
}, delay);
});
}
// 添加任务
queue.add(asyncTask(1, 2000));
queue.add(asyncTask(2, 1000));
queue.add(asyncTask(3, 1500));
queue.add(asyncTask(4, 500));
处理任务结果
如果需要获取任务结果,可以修改add方法返回Promise。
class ConcurrentQueue {
// ...其他代码同上
add(task) {
return new Promise((resolve, reject) => {
const wrappedTask = () => {
return Promise.resolve(task()).then(resolve, reject);
};
this.queue.push(wrappedTask);
this.next();
});
}
}
错误处理
确保任务失败时不会中断队列运行。
class ConcurrentQueue {
// ...其他代码同上
next() {
while (this.running < this.concurrency && this.queue.length) {
const task = this.queue.shift();
task()
.catch(error => console.error('Task failed:', error))
.finally(() => {
this.running--;
this.next();
});
this.running++;
}
}
}
高级功能扩展
可以添加暂停、继续和清空队列等功能。

class ConcurrentQueue {
constructor(concurrency) {
this.concurrency = concurrency;
this.running = 0;
this.queue = [];
this.paused = false;
}
pause() {
this.paused = true;
}
resume() {
this.paused = false;
this.next();
}
clear() {
this.queue = [];
}
// ...其他方法同上
}
性能考虑
对于大量任务,可以考虑使用链表代替数组实现队列,以提高shift操作性能。






