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

RxJS如何实现按顺序发送POST请求?仅前一个完成后再发下一个

解决方案:实现串行HTTP请求(失败不中断)

要实现前一个请求完成(无论成功/失败)后再发送下一个,核心是用RxJS的concat或concatMap控制串行执行,同时搭配catchError确保单个请求失败不会终止整个序列。

修改后的代码示例

of([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  .pipe(
    // 遍历数组元素,串行处理每个请求
    concatMap((dataArr) => 
      // 用concat按顺序执行每个请求Observable
      concat(
        ...dataArr.map(elem => {
          const obj = {
            title: `foo${elem}`,
            body: `bar${elem}`,
            userId: elem,
          };
          // 单个请求添加错误捕获,避免失败中断后续流程
          return this.http.post(
            `https://jsonplaceholder.typicode.com/posts`,
            obj,
            { headers: { 'Content-type': 'application/json; charset=UTF-8' } }
          ).pipe(
            catchError(err => {
              console.error(`请求userId=${elem}失败:`, err);
              // 返回包含错误信息的Observable,让序列继续执行
              return of({ userId: elem, success: false, error: err.message });
            })
          );
        })
      )
    )
  )
  .subscribe(
    (response) => console.log('请求结果:', response),
    () => console.error('全局错误'),
    () => console.log('所有请求完成')
  );

关键改动说明

  • 替换forkJoin为concat:concat会严格按顺序订阅Observable,只有前一个Observable完成(成功/失败),才会触发下一个,天然实现串行执行。
  • 单个请求绑定catchError:每个请求单独捕获错误,返回正常的Observable(比如带错误信息的对象),避免单个请求失败导致整个序列中断。
  • 取消提前生成请求数组:直接在遍历中创建请求Observable,无需提前初始化所有请求实例。

更简洁的写法

如果不需要保留原始数组的外层Observable,可直接用from转换数组为Observable序列,再用concatMap逐个处理:

from([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
  .pipe(
    concatMap(elem => {
      const obj = {
        title: `foo${elem}`,
        body: `bar${elem}`,
        userId: elem,
      };
      return this.http.post(
        `https://jsonplaceholder.typicode.com/posts`,
        obj,
        { headers: { 'Content-type': 'application/json; charset=UTF-8' } }
      ).pipe(
        catchError(err => {
          console.error(`请求userId=${elem}失败:`, err);
          return of({ userId: elem, success: false, error: err.message });
        })
      );
    })
  )
  .subscribe(
    (res) => console.log('请求结果:', res),
    () => console.error('全局错误'),
    () => console.log('全部请求完成')
  );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 17:20:26