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

如何用RxJS实现Angular HTTP请求分批调用并添加延迟?

问题描述

我有一个由删除请求组成的数组:

const partsArray = parts.map(item => this.partsService.deletePart(item.id));

之前通过forkJoin一次性发起所有删除请求:

forkJoin(partsArray).subscribe({
  error: (error: ApiError) => {
    
  },
  complete: () => {
   
  }
});

但请求数量可能是10个或100个,因此需要分批处理——每处理10次请求后延迟500ms,流程如下:

10 API CALLS 
Delay of 500ms
10 API calls 
Delay of 500ms
...

请问如何用RxJS实现该需求?


实现方案

可以通过RxJS的bufferCount、concatMap、forkJoin和delay操作符组合实现分批延迟处理,具体代码如下:

import { from, forkJoin } from 'rxjs';
import { bufferCount, concatMap, delay } from 'rxjs/operators';

// 将请求数组转为可观察序列
const partsRequest$ = from(partsArray);

partsRequest$
  .pipe(
    // 按每10个请求分组
    bufferCount(10),
    // 按顺序处理每个批次
    concatMap((batch, idx, source) => {
      // 并行发起当前批次的所有请求
      const batch$ = forkJoin(batch);
      // 非最后一批处理完后延迟500ms
      return idx !== source.length - 1 ? batch$.pipe(delay(500)) : batch$;
    })
  )
  .subscribe({
    error: (error: ApiError) => {
      // 错误处理逻辑
    },
    complete: () => {
      // 所有批次处理完成后的逻辑
    }
  });

关键逻辑说明

  • bufferCount(10):自动将请求序列按10个一组拆分,最后一组可能不足10个
  • concatMap:确保批次按顺序执行,前一批的请求全部完成后才会启动下一批
  • 延迟判断:避免最后一批处理完成后额外等待500ms,优化流程效率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 20:15:35