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

如何从Fetch API请求中正确返回获取到的接口数据?

问题原因

你的代码出现undefined是两个问题共同导致的:

  • getViews函数没有把fetch产生的Promise对象返回,函数执行结束默认返回undefined
  • fetch是异步API,调用后不会立刻返回接口结果,不能直接用同步变量的方式接收异步返回值
修复方案

方案1:保留Promise then链写法

首先给fetch加return,再通过then回调接收结果:

var website = "youtube.com"
const getViews = (website) => {
  // 新增return,把Promise对象返回
  return fetch("/api?Action=TrafficHistory&Range=1&Output=json&ResponseGroup=History&Url=" + website, {
    headers: {
      "X-Api-Key": "hidden"
    }
  })
  .then((res) => res.json())
}

// 通过then回调拿到返回数据
getViews(website).then(holdData => {
  console.log(holdData)
  // 所有需要用到holdData的逻辑都要写在这个回调范围内
})

方案2:使用async/await语法(可读性更高)

用ES7的async/await语法简化异步逻辑,写法更贴近同步代码:

var website = "youtube.com"
const getViews = async (website) => {
  const res = await fetch("/api?Action=TrafficHistory&Range=1&Output=json&ResponseGroup=History&Url=" + website, {
    headers: {
      "X-Api-Key": "hidden"
    }
  })
  const holdData = await res.json()
  return holdData
}

// 接收方式1:用then回调
getViews(website).then(holdData => {
  console.log(holdData)
})

// 接收方式2:在async函数内直接用await接收
// async function exec() {
//   const holdData = await getViews(website)
//   console.log(holdData)
// }
// exec()
额外优化提示

你原有代码中res.json()之后先JSON.stringify再JSON.parse的操作是完全多余的,res.json()已经将接口返回的JSON格式数据解析为可直接使用的JS对象,不需要额外做两次转换,可以直接删掉这部分逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 07:21:01