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

setInterval中调用axios get函数无法获取返回数据问题排查

问题原因与解决方法

你的代码核心问题是fetch_data函数没有返回axios请求的Promise对象,导致await fetch_data()无法获取到请求结果,最终data变量一直是初始的null。

具体问题点

  1. fetch_data声明为async函数,但内部执行axios.get后没有返回这个Promise,函数默认返回undefined,所以await之后得不到请求数据。
  2. 原代码的catch块里使用了未定义的callback,这会导致报错,且无法让外层的try/catch捕获错误。

修正后的代码方案

方案一:补全返回Promise

async function fetch_data() {
  // 关键:返回axios请求的Promise
  return axios
    .get("https://url.tld/data")
    .then((res) => {
      console.log(res.data);
      return res.data;
    })
    .catch((error) => {
      // 抛出错误,让外层try/catch捕获
      throw new Error("could not fetch data");
    });
}

setInterval(async () => {
  let data = null;
  try {
    data = await fetch_data();
    console.log("Fetched data:", data); // 现在能正确拿到数据
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}, 60000);

方案二:用async/await改写fetch_data(更简洁)

async function fetch_data() {
  try {
    const res = await axios.get("https://url.tld/data");
    console.log(res.data);
    return res.data;
  } catch (error) {
    throw new Error("could not fetch data");
  }
}

setInterval(async () => {
  let data = null;
  try {
    data = await fetch_data();
    console.log("Fetched data:", data);
  } catch (error) {
    console.error("Error fetching data:", error);
  }
}, 60000);

核心总结

  • async函数的本质是返回Promise,必须确保函数内部返回了异步操作的Promise,await才能获取到结果。
  • 异步错误处理要统一:要么用.catch链式处理,要么用try/catch捕获,避免混用未定义的回调函数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 01:43:26