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

使用async/await通过Axios获取响应及结果提取问题

解决Axios异步函数返回值无法通过.then()获取的问题

你的问题核心在于**getData函数没有正确返回异步请求的结果**,导致后续调用.then()拿不到预期的res。我来帮你梳理问题并修改代码:

原代码的问题点

  1. 虽然你用了await调用Axios,但整个getData函数没有把请求结果return出去——async函数默认会返回一个resolve为undefined的Promise,所以后续.then()拿到的是undefined。
  2. 你同时混用了async/await和.then().catch(),这种写法不仅冗余,还容易导致返回值“丢失”(.then()里的return res只是回调函数的返回值,不会传递到外层的getData函数)。

修改后的代码

我们可以简化写法,用纯async/await风格,确保正确返回请求结果:

'use strict'
async function getData() {
  try {
    const ip = location.host;
    // 直接用await获取响应对象
    const res = await axios({
      url: `${http()}${ip}/getData`,
      method: 'POST',
      timeout: 8000,
      headers: {
        'Content-Type': 'application/json',
      }
    });
    console.dir(res); // 正常打印响应
    return res; // 关键:把响应结果return出去,让getData()的Promise resolve这个值
  } catch (err) {
    console.error(err);
    // 抛出错误,让调用方的.catch()能捕获到异常
    throw err;
  }
}

正确调用方式

现在你就可以通过.then()获取返回的结果了:

let dataObj;
getData()
  .then(function(result) {
    dataObj = result;
    // 在这里处理拿到的JSON数据
    console.log('获取到的数据:', dataObj);
  })
  .catch(function(err) {
    // 处理请求失败的情况
    console.error('请求出错:', err);
  });

额外小提示

如果习惯用async/await,调用时也可以写成这样(更简洁):

async function handleData() {
  try {
    let dataObj = await getData();
    console.log('获取到的数据:', dataObj);
  } catch (err) {
    console.error('请求出错:', err);
  }
}
// 调用函数
handleData();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:53:11