setInterval中调用axios get函数无法获取返回数据问题排查
问题原因与解决方法
你的代码核心问题是fetch_data函数没有返回axios请求的Promise对象,导致await fetch_data()无法获取到请求结果,最终data变量一直是初始的null。
具体问题点
fetch_data声明为async函数,但内部执行axios.get后没有返回这个Promise,函数默认返回undefined,所以await之后得不到请求数据。- 原代码的
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
相关产品推荐
相关产品推荐

