Promise.all执行报错throttle queue is over max capacity如何解决
错误原因说明
你遇到的throttle queue is over max capacity是第三方API调用库的限流队列溢出错误,触发原因如下:
- 你的代码中调用
getOHLCV时会立即发起API请求,当你遍历完所有交易对和时间周期后,相当于一次性触发了几十到上百个并发请求 - 你使用的第三方API库内部自带限流保护逻辑,超过默认并发数的请求会被放到等待队列中排队,当等待队列的长度超过库设置的最大阈值时,就会抛出这个错误
- 如果你的交易对和时间周期数量越多,触发该错误的概率越高
修复方案
方案1:手动限制请求并发数(最稳妥)
不要一次性触发所有请求,改成按固定并发数分批执行,避免请求队列溢出,参考修改代码如下:
// 批量执行工具:可自定义最大并发数,避免一次性请求过多 const batchRequest = async (taskList, maxConcurrency = 4) => { const result = []; let currentIndex = 0; while (currentIndex < taskList.length) { // 截取当前批次的任务 const currentBatch = taskList.slice(currentIndex, currentIndex + maxConcurrency); // 执行当前批次所有任务 const batchRes = await Promise.all(currentBatch.map(task => task())); result.push(...batchRes); currentIndex += maxConcurrency; } return result; } async analyze() { const markets = Object.values(this.service.getMarkets()).filter( (m) => this.markets.includes(m.quoteId) && m.active ); // 注意这里存的是返回请求的函数,不是直接执行请求,避免一次性触发所有API调用 const requestTasks = []; for (let i = 0; i < markets.length; i++) { const symbol = markets[i].symbol; for (let j = 0; j < this.timeframes.length; j++) { const timeframe = this.timeframes[j]; requestTasks.push(() => this.service.getOHLCV(symbol, timeframe)); } } console.log("待执行任务数", requestTasks.length); const startTime = Date.now(); // 可根据实际情况调整maxConcurrency的数值,直到不会触发限流即可 const ohlcvDatasets = await batchRequest(requestTasks, 4); const endTime = Date.now() - startTime; console.log(`${requestTasks.length}个任务执行耗时${endTime} ms`); this.analyzeRSI(ohlcvDatasets); }
方案2:调整第三方库的限流配置
如果所使用的第三方库支持参数配置,可以找到对应的限流配置项,调大限流队列的最大容量,或者提高库默认的并发请求上限。但该方案不推荐使用,因为第三方API本身也有请求频率限制,调大配置后可能会触发API侧的429频率限制错误。
内容的提问来源于stack exchange,提问作者user16780074
相关产品推荐
相关产品推荐

