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

JS中fetch封装函数return返回undefined但console.log正常如何解决

问题原因
  • fetchData 函数无显式返回值:你在函数内部仅将fetch的异步调用链赋值给了request变量,没有将该值返回,JavaScript中无return语句的函数默认返回undefined,这是你直接打印res得到undefined的核心原因。
  • fetch是异步API:它的返回值为Promise对象,即使你正确返回了异步调用链,也无法同步拿到接口返回的最终结果,必须通过Promise的then回调或者async/await语法获取异步resolve的值。
  • 额外细节:你现有过滤逻辑中未处理未传入name参数的场景,此时第二个then回调无返回值,会导致异步结果为undefined。
修复方案

方案1:基于Promise then的写法

首先补全fetchData的返回逻辑:

const fetchData = ({ name, num }) => {
  // 新增return,将fetch返回的Promise暴露给外部调用方
  return fetch(`apiLink`)
    .then((res) => res.json())
    .then(data => {
      if (name) {
        return data.filter(person => person.name.includes(name));
      }
      // 补充无name参数时的返回逻辑
      return data;
    })
    .catch(() => {
      console.error('oh no');
      // 错误场景按需返回默认值,也可以抛出错误由上层处理
      return [];
    })
}

调用时通过then获取最终结果:

fetchData({ name: 'Tina' }).then(res => {
  console.log(res); // 可正常输出过滤后的数组
})

方案2:基于async/await的写法(更易读,推荐)

const fetchData = async ({ name, num }) => {
  try {
    const res = await fetch(`apiLink`);
    const data = await res.json();
    if (name) {
      return data.filter(person => person.name.includes(name));
    }
    return data;
  } catch (err) {
    console.error('oh no', err);
    return [];
  }
}

// 调用示例:在async函数内用await接收结果
const getFilteredData = async () => {
  const res = await fetchData({ name: 'Tina' });
  console.log(res);
}
getFilteredData();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:30:02