You need to enable JavaScript to run this app. 并行调用两个API的实现方法及this.data未定义报错的解决方案
优惠活动
大模型
产品
解决方案
定价
更多

并行调用两个API的实现方法及this.data未定义报错的解决方案

并行API调用实现方案

原来的串行写法总等待时长是两个API响应时间的总和,并行实现可以让两个请求同时从前端发出,总等待时长仅等于两个请求里响应最慢的那个的耗时,能有效压缩等待时间。
并行调用的标准实现方式是使用Promise.all,核心逻辑是先发起所有请求拿到Promise实例,再统一等待所有请求完成,具体代码改写如下:

// 第一步:同时发起两个API请求,不要提前加await
const req1 = this.processService.workflowAPI1('activiti$requisitionandpo', 'COMPLETED');
const req2 = this.processService.workflowAPI(selected_actID);

// 第二步:统一等待所有请求完成
try {
  const [res1, res2] = await Promise.all([req1, req2]);
  // 第三步:请求全部返回后再给组件变量赋值
  this.data = res1;
  this.APIresponse = res2;
  console.log(this.APIresponse);
  this.spinner.hide();
  this.showTable = true;
} catch (error) {
  // 捕获请求阶段的异常,避免未捕获的Promise报错
  this.spinner.hide();
  console.error('请求失败', error);
}

常见踩坑:如果在数组元素里写await 接口1、await 接口2,本质还是从左到右串行发请求,达不到并行效果。

解决Cannot read property 'forEach' of undefined报错

这个报错的根本原因是:执行this.data.forEach遍历逻辑的时候,this.data还没有被赋值——也就是遍历代码的执行位置跑到了Promise.all的等待逻辑之前,JS代码跳过了异步等待的过程,直接同步执行了遍历,此时this.data还是初始的undefined。
修正方式很简单,所有依赖this.data的后续处理逻辑,必须放到Promise.all成功返回、this.data完成赋值的代码块后面,示例顺序如下:

const req1 = this.processService.workflowAPI1('activiti$requisitionandpo', 'COMPLETED');
const req2 = this.processService.workflowAPI(selected_actID);

try {
  const [res1, res2] = await Promise.all([req1, req2]);
  this.data = res1;
  this.APIresponse = res2;
  this.spinner.hide();
  this.showTable = true;

  // 从这里开始写依赖this.data的遍历逻辑
  const arraynew = []; // 记得提前初始化arraynew,避免未定义报错
  (this.data || []).forEach(element => { // 加空值兜底,避免接口返回空值时报错
    element['properties'] = element.properties.map;
    columns.forEach(column => {
      if (column.header == 'PO Number') {
        if (column.hasMulValue) {
          column.value_list.forEach(value => {
            var column_value = this.adminService.loadColumnValue(value, element);
            if (column_value != null && column_value != '0') {
              element['po_num'] = column_value;
            }
          })
        }
      }
    })
    var x = new Date(element.properties.completionDate);
    var y = new Date("Oct 18, 2020");
    if ((element.taskType == "aclrq:PreparePo") && (x > y)) {
      arraynew.push(element)
    }
  })

  // 遍历完成后的后续逻辑正常写即可
} catch (error) {
  this.spinner.hide();
  console.error('处理流程异常', error);
}

补充几个容易遗漏的细节:

  • 记得提前初始化遍历要用的arraynew变量,不然首次执行的时候也会报未定义的错
  • 给遍历的目标加空值兜底,万一接口返回空值、请求异常,不会直接中断整个流程
  • Promise.all只要有一个请求失败,就会直接进入catch块,不会等其他请求返回,所以一定要加try-catch包裹整个异步流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.19 09:54:04