VSCode扩展中监控Promise数组单个请求完成并维持5并发调用
固定并发量的请求池实现(带token偏移绑定)
核心思路
放弃整批等待的Promise.all模式,为每个并发槽位创建独立的任务循环:
- 初始化5个并发槽位,每个槽位对应固定的token初始偏移(0到4)
- 每个槽位循环执行:取出对应偏移的token → 发起请求 → 请求完成后,取下一个同偏移的token(偏移+5)继续执行
- 所有槽位的任务循环结束后,整体任务完成
代码实现
// 假设你已准备好: // 1. 不可复用的token数组,按顺序匹配请求 // 2. 单个请求的实现逻辑 const tokens = ['token0', 'token1', 'token2', 'token3', 'token4', 'token5', ...]; // 你的token列表 const concurrency = 5; // 固定并发数 // 单个REST请求函数,接收token和请求索引,返回Promise async function makeRequest(token, requestIndex) { // 替换为你的VSCode扩展中实际的API调用逻辑 // 比如使用node-fetch、axios或VSCode内置的请求能力 const response = await fetch('你的API地址', { headers: { 'Authorization': `Bearer ${token}` }, // 其他请求参数(如method、body等) }); const result = await response.json(); console.log(`请求 ${requestIndex} 完成,使用token: ${token}`); return result; } // 单个并发槽位的任务循环 async function worker(slotIndex) { let currentIndex = slotIndex; while (currentIndex < tokens.length) { const token = tokens[currentIndex]; try { await makeRequest(token, currentIndex); } catch (error) { // 处理请求错误,比如记录日志或添加重试逻辑 console.error(`请求 ${currentIndex} 失败`, error); } currentIndex += concurrency; // 取下一个同槽位的token(偏移+5) } } // 启动所有并发任务 async function startAllRequests() { const workerPromises = []; for (let i = 0; i < concurrency; i++) { workerPromises.push(worker(i)); } // 等待所有槽位的任务循环结束 await Promise.all(workerPromises); console.log('所有请求执行完成'); } // 触发请求执行 startAllRequests();
方案优势
- 维持稳定并发:每个槽位的请求完成后立即发起下一个,始终保持5个请求在运行(直到所有任务完成)
- 精准绑定token偏移:每个槽位对应固定的初始偏移,后续请求自动沿用该偏移的步进规则,完全符合token不可复用的要求
- 实时响应单个请求完成:无需等待整批请求结束,单个请求完成后立即触发下一个,提升整体执行效率
额外优化建议
- 错误重试:可在
makeRequest的catch块中添加重试逻辑,避免单个请求失败中断槽位任务 - 进度监控:维护全局计数器,实时记录已完成请求数,方便在VSCode界面展示进度
- 请求取消:引入AbortController,支持随时终止所有未完成的请求
内容的提问来源于stack exchange,提问作者djacks
相关产品推荐
相关产品推荐

