You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Promise分批限流,每次最多同时执行50个异步任务

限流分批实现方案

前置修正点

你现有代码存在逻辑错误:判断条件if(simIds.length < 0)永远不会成立(数组长度不可能为负数),需要先修正为if(simIds.length > 0)才会执行内部逻辑。

核心实现思路

将simIds数组按单批最大并发数(这里设为50)切割为多个子数组,逐批次串行执行:单批次内的请求并行执行,当前批次全部请求完成后再进入下一批次,既控制并发上限,又保证执行效率。

完整可运行代码

// 单批最大并发数,可根据实际情况调整
const MAX_BATCH_SIZE = 50;
// 存储所有请求的返回结果,顺序和simIds原始顺序一致
const totalResults = [];

if (simIds.length > 0) {
  // 第一步:将simIds按批次大小切割为多个子数组
  const batches = [];
  for (let i = 0; i < simIds.length; i += MAX_BATCH_SIZE) {
    batches.push(simIds.slice(i, i + MAX_BATCH_SIZE));
  }

  // 第二步:串行处理每个批次
  (async function runBatches() {
    for (const currentBatch of batches) {
      // 生成当前批次的所有请求Promise
      const batchPromises = currentBatch.map(simid => {
        return new Promise(resolve => {
          simService.getSimcardBasedonAction(userid, [simid], action)
            .then(result => {
              if (result.success) {
                // 保留原有的simDetail处理逻辑
                const simDetail = result.simcards[0];
              }
              resolve(result);
            })
        })
      })
      // 等待当前批次所有请求完成
      const batchRes = await Promise.all(batchPromises);
      totalResults.push(...batchRes);
    }
    // 所有批次处理完成后的后续逻辑
    console.log('全部请求执行完成,总结果:', totalResults);
  })();
}

兼容不支持async/await的场景

如果你的运行环境不支持ES7的async/await语法,可以用Promise链式调用实现:

const MAX_BATCH_SIZE = 50;
const totalResults = [];

if (simIds.length > 0) {
  const batches = [];
  for (let i = 0; i < simIds.length; i += MAX_BATCH_SIZE) {
    batches.push(simIds.slice(i, i + MAX_BATCH_SIZE));
  }

  let batchProcessor = Promise.resolve();
  batches.forEach(currentBatch => {
    batchProcessor = batchProcessor.then(() => {
      const batchPromises = currentBatch.map(simid => {
        return new Promise(resolve => {
          simService.getSimcardBasedonAction(userid, [simid], action)
            .then(result => {
              if (result.success) {
                const simDetail = result.simcards[0];
              }
              resolve(result);
            })
        })
      })
      return Promise.all(batchPromises).then(batchRes => {
        totalResults.push(...batchRes);
      })
    })
  })

  batchProcessor.then(() => {
    console.log('全部请求执行完成,总结果:', totalResults);
  })
}

扩展说明

  • 如果需要处理单个请求报错不阻塞整批的场景,可以在单个Promise中添加catch逻辑,将错误信息也作为返回结果存入数组即可
  • 可以根据服务端限流规则灵活调整MAX_BATCH_SIZE的数值,优化执行效率

内容的提问来源于stack exchange,提问作者Profer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 10:39:02