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

Node.js函数无法返回值求助:如何获取正确返回结果?

Node.js异步函数返回undefined问题解决

你的getBBBMeetingInfo函数返回undefined的核心原因是异步操作的执行顺序问题:

  • bbbHttp(getMeetingInfo)是异步Promise操作,.then()回调里的代码会在HTTP请求完成后才执行
  • 函数本身会直接跳过异步逻辑,先执行return val,此时val还未被赋值,自然是undefined

下面是两种可行的修改方案:

方案1:让函数返回Promise

直接返回异步操作的Promise,在回调中返回最终需要的值:

const getBBBMeetingInfo = (meetingID) => {
    let bbbHttp = bbb.http;
    let getMeetingInfo = api.monitoring.getMeetingInfo(meetingID);
    
    // 返回Promise,在then中传递最终结果
    return bbbHttp(getMeetingInfo).then((result) => {
      let newRes = { ...result };
      newRes.meetingID = meetingID;
      if(newRes.returncode === 'FAILED'){
        updateNotificationCallStatus(meetingID)
      }  
      return newRes.returncode;
    });
}

调用时需要通过.then()接收结果,或者在async函数中用await:

// 方式1:使用then回调
getBBBMeetingInfo(ele.meetingId).then(bn => {
  console.log(bn); // 此处可拿到正确返回值
});

// 方式2:在async函数中使用await
async function getMeetingData() {
  let bn = await getBBBMeetingInfo(ele.meetingId);
  console.log(bn);
}
getMeetingData();

方案2:使用async/await简化异步逻辑

将函数声明为async,用await等待异步操作完成,代码更直观:

const getBBBMeetingInfo = async (meetingID) => {
    let bbbHttp = bbb.http;
    let getMeetingInfo = api.monitoring.getMeetingInfo(meetingID);
    
    // 等待异步请求完成,直接拿到结果
    const result = await bbbHttp(getMeetingInfo);
    let newRes = { ...result };
    newRes.meetingID = meetingID;
    if(newRes.returncode === 'FAILED'){
      updateNotificationCallStatus(meetingID)
    }  
    return newRes.returncode;
}

调用时必须在async函数中使用await:

async function fetchAndLogInfo() {
  let bn = await getBBBMeetingInfo(ele.meetingId);
  console.log(bn);
}
fetchAndLogInfo();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 14:20:42