class AsyncQueue {
constructor() {
this.queue = [];
this.running = false;
}
// 向队列中添加一个异步任务
add(task) {
this.queue.push(task);
if (!this.running) {
this.execute();
}
}
// 执行队列中的任务
async execute() {
if (this.queue.length === 0) {
this.running = false;
return;
}
this.running = true;
const task = this.queue.shift();
try {
await task();
} catch (error) {
console.error('任务执行失败:', error);
}
this.execute();
}
}
// 使用示例
const asyncQueue = new AsyncQueue();
// 添加异步任务到队列
asyncQueue.add(async () => {
console.log('任务1开始');
await someAsyncFunction1();
console.log('任务1完成');
});
asyncQueue.add(async () => {
console.log('任务2开始');
await someAsyncFunction2();
console.log('任务2完成');
});
// ...
// 添加更多任务...
// 当你添加了足够的任务后,队列会按顺序开始执行
实现一个异步串行队列
最新推荐文章于 2024-08-15 08:55:57 发布