You need to enable JavaScript to run this app. data.map循环调用异步函数时执行顺序错乱,使用async/await未生效
优惠活动
大模型
产品
解决方案
定价
更多

data.map循环调用异步函数时执行顺序错乱,使用async/await未生效

异步请求顺序异常问题的修复方案

现有代码的核心缺陷

  • 循环调用未做等待处理:使用map遍历数组直接调用getEventDetails时,没有对方法返回的Promise做await等待,所有请求几乎同时被触发发出,没有形成可控的执行链路
  • 手动封装Promise逻辑失效:getEventDetails内部通过new Promise封装请求逻辑,但从未在post请求的回调中调用myResolve()标记Promise完成状态,导致await myPromise的等待逻辑完全不生效
  • 网络响应天然无顺序保证:并发触发的多个接口请求,返回顺序由网络时延、后端处理耗时决定,不受遍历代码的先后顺序控制,最终就会出现回调中输出的index值和遍历顺序不一致的问题

修复后的实现逻辑

第一步:修正getEventDetails的方法实现

去掉冗余的手动Promise封装,利用async方法本身的Promise特性补全逻辑:

getEventDetails = async (value, index) => {
  console.log("Index Value at the entry--->", index);
  const data = {
    accountName: "test",
  };
  const url = `/rest/jarvis/reports/v1/getBetEventData`;
  try {
    const response = await post(url, data);
    if (response.data) {
      console.log("Index Value inside--->", index);
      // 补全原代码中缺失的事件键取值逻辑
      const eventKey = value.eventId != null ? value.eventId : this.props.bs.betEventRequest.EventId;
      this.eventIdIndexMap.set(eventKey, index);
      // 直接用index作为下标存储结果,避免map取值的冗余逻辑
      this.props.bs.testEventDetails[index] = response.data;
    }
  } catch (error) {
    console.error(`第${index}条赛事详情请求失败`, error);
  }
}

第二步:根据业务需求选择合适的循环调用方式

首先需要将外层的getDetails方法改为async修饰,保证内部可以正常使用await语法:

getDetails = async (inputData) => {
  const data = { accountName: "test" };
  const url = `/rest/jarvis/reports/v1/getData`;
  const response = await post(url, data);
  if (!(response.data && response.data.sb?.length > 0)) return;
  
  this.props.bs.betDetails = {
    data: [...response.data.sportsbookBets],
    exportAccesses: response.data.exportAccesses,
  };
  // 此处替换原map循环的逻辑
}

方案1:严格串行执行(完全匹配顺序执行要求)

逐次触发请求,前一个请求完全处理完成后,再触发下一个请求,保证回调的index输出、数据写入完全和数组原始顺序一致:

// 替换原map循环块
for (const [index, value] of this.props.bs.betDetails.data.entries()) {
  console.log("Index Value --->", index);
  // 等待当前请求完全处理完成后,再进入下一次循环
  await this.getEventDetails(value, index);
}
// 所有请求全部处理完成后,再更新全局状态
this.updateReducer({ ...this.props.bs });

注意:串行执行的总耗时为所有单个请求的耗时总和,网络利用率较低,适合数据量小、需要严格顺序控制的场景。

方案2:并发请求+顺序聚合(兼顾效率和顺序一致性)

同时发起所有请求,不限制请求的发出顺序,但等所有请求全部完成后,再统一做后续状态更新,保证最终结果和原数组顺序对齐:

// 替换原map循环块
// 收集所有请求的Promise实例
const requestList = this.props.bs.betDetails.data.map(
  (value, index) => this.getEventDetails(value, index)
);
// 等待所有请求完成,结果顺序和原数组下标严格对应
await Promise.all(requestList);
// 所有请求全部处理完成后,再更新全局状态
this.updateReducer({ ...this.props.bs });

注意:该方案的总耗时为所有请求中最长的单请求耗时,执行效率远高于串行方案,仅要求最终结果顺序一致时优先选择该方案。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.29 00:27:07