实现 javascript 中的 async/await 错误重试队列,核心思路是维护一个任务列表和一个执行器循环。执行器不断从队列中取出任务,使用 try/catch 包裹异步调用,若失败则根据配置进行指数退避等待后重新入队或立即重试,直到成功或达到最大重试次数。这种方式能确保任务按顺序或并发度限制被可靠处理,避免一次性全部失败导致的雪崩。

如何设计支持指数退避的重试逻辑
重试逻辑的关键在于计算等待时间并控制重试上限。通常采用指数退避策略,即每次重试的等待时间随重试次数呈指数增长,例如 baseDelay * 2^attempt。在代码实现中,需要在循环内判断当前重试次数是否超过 maxRetries,若未超过则计算 delay 并 await Promise.resolve(delay),然后继续下一次尝试;若超过则抛出最终错误。这种机制能有效应对临时性故障(如网络抖动、服务限流),给下游系统恢复的时间。

function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function retryWithBackoff(taskFn, maxRetries = 3, baseDelay = 1000) {
let attempt = 0;
while (true) {
try {
return await taskFn();
} catch (error) {
attempt++;
if (attempt > maxRetries) {
throw error;
}
const delay = baseDelay * Math.pow(2, attempt - 1);
console.log(`Retry ${attempt}/${maxRetries} after ${delay}ms`);
await sleep(delay);
}
}
}
上述代码展示了单个任务的重试封装。taskFn 是被包装的异步操作。当 taskFn 抛出异常时,进入 catch 块。如果 attempt 小于等于 maxRetries,计算延迟并等待,然后循环继续。如果超过次数,则向上抛出错误。调用方可以使用这个函数来包装任何可能失败的异步操作。
立即学习“Java免费学习笔记(深入)”;
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
如何构建基于优先级的任务队列
构建任务队列需要管理任务的加入和取出。一个简单的实现是使用数组作为队列,但为了支持优先级,可以使用最小堆或排序数组。更常见的做法是维护一个普通队列,但在取出任务时根据优先级排序,或者为不同优先级的任务维护多个队列。这里展示一个简单的高优先级先执行的队列模型:新任务插入时,如果优先级高,则插入到队列头部;否则插入尾部。执行器从队列头部取出任务进行处理。
class PriorityQueue {
constructor() {
this.tasks = [];
}
enqueue(task, priority = 0) {
// 简单实现:高优先级(数值大)插在前面
let inserted = false;
for (let i = 0; i < this.tasks.length; i++) {
if (priority > this.tasks[i].priority) {
this.tasks.splice(i, 0, { task, priority });
inserted = true;
break;
}
}
if (!inserted) {
this.tasks.push({ task, priority });
}
}
dequeue() {
return this.tasks.shift();
}
isEmpty() {
return this.tasks.length === 0;
}
}
PriorityQueue 类提供了基本的入队和出队功能。enqueue 方法根据 priority 参数决定插入位置,priority 越大越靠前。dequeue 移除并返回第一个元素。isEmpty 检查队列是否为空。结合之前的 retryWithBackoff 函数,可以将每个任务包装成带重试逻辑的执行单元。
如何处理队列满时的背压(Backpressure)
当任务生产速度远大于消费速度时,队列会无限增长导致内存溢出。解决背压问题的常见策略是限制队列大小,并在队列满时阻塞生产者或拒绝新任务。在异步环境中,可以通过 Promise 来实现阻塞:当队列满时,生产者等待一个信号量,直到有空间释放。另一种方式是直接 reject 新任务,让调用方处理。这里展示一种简单的固定容量队列,满时等待:
class BoundedQueue {
constructor(maxSize) {
this.maxSize = maxSize;
this.queue = [];
this.waitingProducers = [];
}
async enqueue(task, priority = 0) {
if (this.queue.length >= this.maxSize) {
// 等待空间
await new Promise(resolve => this.waitingProducers.push(resolve));
}
// 插入任务
let inserted = false;
for (let i = 0; i < this.queue.length; i++) {
if (priority > this.queue[i].priority) {
this.queue.splice(i, 0, { task, priority });
inserted = true;
break;
}
}
if (!inserted) {
this.queue.push({ task, priority });
}
// 如果有等待的生产者,通知一个
if (this.waitingProducers.length > 0) {
const resolve = this.waitingProducers.shift();
resolve();
}
}
dequeue() {
return this.queue.shift();
}
isEmpty() {
return this.queue.length === 0;
}
size() {
return this.queue.length;
}
}
BoundedQueue 限制了队列最大长度为 maxSize。当 enqueue 时如果已满,生产者会 await 一个 Promise,该 Promise 由 dequeue 操作完成后触发(此处简化,实际应在 dequeue 后通知)。这确保了队列不会无限膨胀。结合执行器循环,可以创建一个稳定的任务处理系统。
完整执行器与集成示例
将上述组件组合成一个完整的重试队列执行器。执行器是一个异步函数,它持续从队列中取出任务,执行重试逻辑,直到队列为空或收到停止信号。以下是一个简化的集成示例:
class RetryQueueExecutor {
constructor(queue, concurrency = 1) {
this.queue = queue;
this.concurrency = concurrency;
this.running = false;
}
async start() {
this.running = true;
const workers = Array.from({ length: this.concurrency }, () => this.worker());
await Promise.all(workers);
}
async worker() {
while (this.running && !this.queue.isEmpty()) {
const item = this.queue.dequeue();
if (!item) break;
const { task, priority } = item;
try {
await retryWithBackoff(task, 3, 1000);
console.log('Task completed successfully');
} catch (error) {
console.error('Task failed after retries:', error.message);
}
}
}
stop() {
this.running = false;
}
}
// 使用示例
const q = new BoundedQueue(10);
const executor = new RetryQueueExecutor(q, 2);
executor.start();
// 添加任务
q.enqueue(async () => { /* 异步操作 */ }, 5);
q.enqueue(async () => { /* 异步操作 */ }, 1);

















