js 实现一个任务队列
实现基础任务队列结构
使用数组存储任务,通过 push 方法添加任务,shift 方法按顺序取出任务执行:
class TaskQueue {
constructor() {
this.tasks = [];
this.isRunning = false;
}
addTask(task) {
this.tasks.push(task);
if (!this.isRunning) this.run();
}
async run() {
this.isRunning = true;
while (this.tasks.length > 0) {
const task = this.tasks.shift();
try {
await task();
} catch (error) {
console.error('Task failed:', error);
}
}
this.isRunning = false;
}
}
支持并发控制
限制同时执行的任务数量,避免资源过载:
class ConcurrentQueue {
constructor(concurrency = 1) {
this.tasks = [];
this.concurrency = concurrency;
this.running = 0;
}
addTask(task) {
this.tasks.push(task);
this.next();
}
next() {
while (this.running < this.concurrency && this.tasks.length) {
const task = this.tasks.shift();
this.running++;
task().finally(() => {
this.running--;
this.next();
});
}
}
}
优先级队列实现
通过优先级字段控制任务执行顺序:
class PriorityQueue {
constructor() {
this.tasks = [];
}
addTask(task, priority = 0) {
this.tasks.push({ task, priority });
this.tasks.sort((a, b) => b.priority - a.priority);
}
async run() {
while (this.tasks.length > 0) {
const { task } = this.tasks.shift();
await task();
}
}
}
错误处理与重试机制
为任务添加自动重试逻辑,提高容错性:
class RetryQueue {
constructor(maxRetries = 3) {
this.tasks = [];
this.maxRetries = maxRetries;
}
addTask(task) {
this.tasks.push(async () => {
let retries = 0;
while (retries <= this.maxRetries) {
try {
await task();
break;
} catch (error) {
retries++;
if (retries > this.maxRetries) throw error;
}
}
});
}
async run() {
while (this.tasks.length > 0) {
const task = this.tasks.shift();
await task();
}
}
}
使用示例
基础队列调用方式:
const queue = new TaskQueue();
queue.addTask(() => console.log('Task 1'));
queue.addTask(() => new Promise(resolve => setTimeout(resolve, 1000)));
并发队列调用方式:

const concurrentQueue = new ConcurrentQueue(2);
for (let i = 0; i < 5; i++) {
concurrentQueue.addTask(() => new Promise(resolve => {
setTimeout(() => resolve(console.log(`Task ${i}`)), 500);
}));
}






