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

包含axios调用的for循环中async await的正确行为是什么?

问题核心原因
  • 最核心的问题是getMeetingAgenda函数没有显式返回请求结果:你在.then()回调里写的return response.data.agenda仅作用于回调函数本身,整个async函数没有将这个结果向外返回,所以await getMeetingAgenda()拿到的永远是undefined。
  • 你之前猜测的for循环没有等待的问题不存在:普通for循环内的await会按顺序阻塞执行,从你打印的日志顺序(先打印getMeetingAgenda内的议程,再打印getDesiredRecordings内的ID日志)也能验证等待逻辑是生效的。
  • 额外的逻辑瑕疵:你把getMeetingAgenda的调用写在if判断外的三元运算符里,可能会给无效的会议ID也在meetingAgendas里生成值为undefined的键,属于冗余逻辑。
修复方案

1. 修正getMeetingAgenda的返回逻辑,同时统一异步写法(不要混用await和.then,避免逻辑混乱)

async function getMeetingAgenda(meetingId, config) {
  console.log(meetingId)
  try {
    const response = await axios.get(`${Zoom_Agenda_End_Point}${meetingId}`, config)
    console.log(response.data.agenda);
    return response.data.agenda;
  } catch(e) {
    console.log("Axios error occured in getMeetingAgenda: ",e);
    return "";
  }
}

如果你还是想用.then的写法,直接return整个axios请求即可:

async function getMeetingAgenda(meetingId, config) {
  console.log(meetingId)
  // 加return把整个Promise的结果向外返回
  return axios.get(`${Zoom_Agenda_End_Point}${meetingId}`, config)
    .then(function (response) {
      console.log(response.data.agenda);
      return response.data.agenda;
    })
    .catch(e=>{
      console.log("Axios error occured in getMeetingAgenda: ",e);
      return "";
    });
}

2. 优化getDesiredRecordings内的调用逻辑,移除冗余的三元运算符

async function getDesiredRecordings(recordings, config) {
  try {
    let requiredMeetings = [];
    if (!recordings || !recordings.length) {
      // 修正空值返回结构,和调用处的结构对齐
      return {
        meetingIds: [],
        requiredMeetings: [],
        meetingAgendas: {}
      };
    }
    let meetingIds = [];
    let meetingAgendas = {};
    console.log(config)
    for (let i = 0; i < recordings.length; i++) {
      const currentRecording = recordings[i]
      if (currentRecording && currentRecording.topic && isRecordingValid(currentRecording.topic)) {
        requiredMeetings.push(currentRecording);
        meetingIds.push(currentRecording.id);
        // 仅对有效会议发起请求,避免无效逻辑
        meetingAgendas[currentRecording.id] = await getMeetingAgenda(currentRecording.id,config);
        console.log("getDesiredRecordings ID: ", currentRecording.id, meetingAgendas[currentRecording.id]);
      }
    }
    console.log(meetingAgendas);
    return {
      meetingIds: meetingIds,
      requiredMeetings: requiredMeetings,
      meetingAgendas : meetingAgendas
    };
  }
  catch (e) {
    return Promise.reject(new Error(e));
  }
}

内容的提问来源于stack exchange,提问作者era s'q

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:45:00