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

如何高效合并异步函数结果?异步函数调用及报错问题求助

问题解决与优化方案

一、先解决参考代码的报错

你遇到的ReferenceError: getLiveData is not defined是变量作用域问题:getLiveData是getLive函数内部声明的局部变量,外部的showVideo函数无法访问。同时你的逻辑判断写反了,需求是「getLive返回数据则用它,空则用getArchived」,原代码的if条件刚好相反。

修正后的参考代码:

async function getLive(){
  const response = await fetch("video-live");
  return await response.json(); // 直接返回结果,无需额外存变量
}

async function getArchived() {
  const response = await fetch("video-archived");
  return await response.json();
}

async function showVideo() {
  const liveData = await getLive();
  // 根据实际返回格式调整判断逻辑,比如是否为空字符串/空对象
  if (liveData && liveData !== "") { 
    console.log('使用直播数据:', liveData);
  } else {
    const archivedData = await getArchived();
    console.log('使用归档数据:', archivedData);
  }
}

// 调用执行
showVideo();

二、用.then()链式调用整合的方案

如果偏好使用then而非async/await,可以这样实现:

function showVideo() {
  getLive()
    .then(liveData => {
      if (liveData && liveData !== "") {
        console.log('使用直播数据:', liveData);
        return liveData; // 可选,返回数据供后续链式调用
      }
      // 直播数据为空,触发归档接口调用
      return getArchived().then(archivedData => {
        console.log('使用归档数据:', archivedData);
        return archivedData;
      });
    })
    .catch(err => {
      // 捕获请求错误,避免程序崩溃
      console.error('接口请求出错:', err);
    });
}

// 调用执行
showVideo();

三、原showVideo函数的问题说明

你之前用getLive().then(showVideo)调用时,showVideo只会接收到getLive返回的第一个参数,第二个参数getArchivedData并未传递,所以打印结果为undefined。这种方式无法自动触发getArchived的调用,必须在逻辑中手动判断后主动调用第二个接口。

补充提示

  • 数据空值判断需匹配实际接口返回格式:如果接口返回空对象{},则需要用Object.keys(liveData).length === 0来判断,而非liveData == ""。
  • 务必添加错误捕获逻辑,避免接口请求失败时导致控制台报错或程序异常。

内容的提问来源于stack exchange,提问作者Dirty Bird Design

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 03:31:12