JavaScript实现可动态添加的异步函数调用队列以规避API限流
动态异步任务队列实现方案(解决Google Sheets API限流问题)
针对Discord Bot调用Google Sheets API时的限流问题,下面是一个支持动态添加任务的并发队列实现,无需轮询即可自动处理队列任务,同时控制请求频率和并发数:
核心实现代码
class RateLimitedQueue { constructor({ maxConcurrent = 2, requestInterval = 1000 }) { this.queue = []; this.activeCount = 0; this.maxConcurrent = maxConcurrent; this.requestInterval = requestInterval; this.isProcessing = false; } addTask(task) { return new Promise((resolve, reject) => { this.queue.push({ task, resolve, reject }); this.processQueue(); }); } async processQueue() { if (this.isProcessing) return; this.isProcessing = true; while (this.activeCount < this.maxConcurrent && this.queue.length > 0) { const { task, resolve, reject } = this.queue.shift(); this.activeCount++; try { const result = await task(); resolve(result); } catch (error) { reject(error); } finally { this.activeCount--; await new Promise(resolve => setTimeout(resolve, this.requestInterval)); this.processQueue(); } } this.isProcessing = false; } }
使用示例
// 初始化队列:根据Google API限流规则调整参数 // 示例:最多同时执行2个任务,任务间隔1秒 const apiQueue = new RateLimitedQueue({ maxConcurrent: 2, requestInterval: 1000 }); // 封装Google Sheets API调用 async function callGoogleSheetsApi(payload) { // 替换为实际的API调用逻辑 const response = await fetch('https://sheets.googleapis.com/v4/spreadsheets/...', { method: 'POST', headers: { 'Authorization': 'Bearer YOUR_TOKEN' }, body: JSON.stringify(payload) }); if (!response.ok) throw new Error(`API请求失败:${response.status}`); return response.json(); } // Discord事件触发时,将API任务加入队列 async function handleDiscordUserAction(userId, sheetData) { try { const apiResult = await apiQueue.addTask(() => callGoogleSheetsApi(sheetData)); // 处理API结果,比如回复Discord用户 console.log(`用户${userId}的请求已完成:`, apiResult); } catch (err) { // 处理错误,比如告知用户操作失败 console.error(`用户${userId}的请求出错:`, err); } } // 模拟多个用户同时触发操作 handleDiscordUserAction('user123', { range: 'A1:B2', values: [[1,2],[3,4]] }); handleDiscordUserAction('user456', { range: 'C1:D2', values: [[5,6],[7,8]] }); handleDiscordUserAction('user789', { range: 'E1:F2', values: [[9,10],[11,12]] });
关键特性说明
- 动态任务添加:队列运行过程中可以随时通过
addTask加入新任务,无需预定义队列内容 - 并发控制:通过
maxConcurrent限制同时执行的API请求数量 - 请求间隔:通过
requestInterval控制任务执行的时间间隔,避免短时间内请求过多触发限流 - 自动调度:任务完成后自动从队列取出下一个任务执行,无需手动轮询队列
- 错误处理:每个任务的成功/失败结果会通过Promise返回,方便业务层处理
优化建议
- 根据Google Sheets API的具体限流规则(如每分钟请求次数)调整
maxConcurrent和requestInterval参数 - 在API调用函数中添加429错误重试逻辑,配合队列使用可进一步提升可靠性
- 可以为队列添加任务优先级、超时控制等扩展功能,适配更复杂的业务场景
内容的提问来源于stack exchange,提问作者Arpit Ranasaria
相关产品推荐
相关产品推荐

