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

React中使用Axios顺序调用多批依赖API 全部完成后派发成功状态

实现方案

核心需求

  • 根据传入的data数组元素数量,批量调用接口http://sample.com
  • 第一批接口全部调用完成后,取第一批返回的响应数据作为入参,批量调用接口http://sample2.com
  • 两批所有接口全部执行成功后,再派发成功的dispatch动作;任意环节报错则派发失败动作

原代码问题

  • 语法错误:map的回调函数内使用了await,但没有给回调函数加async关键字,await无法正常生效
  • 逻辑漏洞:第二批接口调用后没有用Promise.all等待所有请求执行完成,会导致第二批请求还没跑完就提前派发成功动作
  • 判断逻辑错误:校验code是否存在时,错误判断了外层的productCode变量,没有校验当前遍历项返回的code值
  • 边界缺失:入参data默认值为null,没有做数组类型兜底,null调用.map会直接抛出类型错误
  • 冗余代码:原代码中声明的productCode变量没有实际作用,map遍历没有返回值,属于无效逻辑

修正后代码

export const createAllProducts =
  ({ data = null, isCall2 = false }) =>
  async (dispatch) => {
    try {
      dispatch({
        type: constants.CREATE_ALL_PRODUCTS_REQUEST,
      });

      // 入参兜底,避免data为null时调用map报错
      const sourceList = Array.isArray(data) ? data : [];

      // 第一批批量并发请求
      const firstRequests = sourceList.map(({ test, name }) => {
        return getAxiosService().post("http://sample.com", {
          test,
          name,
        });
      });
      const firstResponses = await Promise.all(firstRequests);

      // 需要调用第二批接口时,收集所有请求并等待全部完成
      if (isCall2) {
        const secondRequests = firstResponses.map((response) => {
          const code = response?.code;
          if (!code) throw new Error("Code not found");
          return getAxiosService().post("http://sample2.com", {
            code,
          });
        });
        // 等待第二批所有并发请求完成
        await Promise.all(secondRequests);
      }

      // 所有请求全部完成后再派发成功动作
      dispatch({
        type: constants.CREATE_ALL_PRODUCTS_SUCCESS,
      });
    } catch (error) {
      dispatch({
        type: constants.CREATE_ALL_PRODUCTS_FAILURE,
      });
    }
  };

补充说明:如果业务要求第二批接口必须串行执行,只需要把第二批的Promise.all逻辑替换为for...of循环逐个await调用即可,上述默认实现为第二批接口并发执行,性能更优。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 16:06:26