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

Node.js异步函数中Axios请求返回值为undefined问题排查

问题:异步函数返回Axios结果时显示undefined

在Node.js异步函数中通过Axios调用获取数组,Axios调用正常,console.log能在Promise的data对象中看到目标数组,但在函数外部打印函数结果时却显示undefined。

代码示例

async function userImport (settings, file) {
  let usersFile;
  const auth = {
    "username": settings.authentication.user,
    "password": settings.authentication.password
  };
  const options = {
    method: 'get',
    headers: {},
    timeout: 10000
  };
  await axios.get(settings.url, auth, options)
    .then((results) => {
      usersFile = results.data;
      console.log(usersFile);
      if (usersFile && usersFile != "" && usersFile != undefined) {
        console.log("Test1");
        return [usersFile, settings.encoding];
      } else {
        console.log("Test2");
        return results;
      }
    })
}

await userImport(settings, file)
  .then(async (users)=>{
    console.log(users);
  })

实际输出

[{...},{...},{...}] //目标数组
Test1
Undefined

预期输出

[{...},{...},{...}] //目标数组
Test1
[{...},{...},{...}] //目标数组

已尝试的方法

  • 将数组放入JSON对象,输出仍为undefined
  • 直接返回results.data,结果相同

解决方案

问题核心有两个:

  1. userImport函数未返回任何值:你在.then()回调中的return属于回调函数本身,不会被外层的userImport函数返回。
  2. Axios参数传递错误:axios.get的参数格式是url[, config],不能单独传递auth作为第二个参数,需将auth放入配置对象中。

推荐使用await的同步写法(避免混用await和.then()),修正后的代码如下:

async function userImport(settings, file) {
  const auth = {
    username: settings.authentication.user,
    password: settings.authentication.password
  };
  const options = {
    method: 'get',
    headers: {},
    timeout: 10000,
    auth // 将auth合并到配置对象中
  };

  // 用await直接获取Axios响应结果
  const results = await axios.get(settings.url, options);
  const usersFile = results.data;
  
  console.log(usersFile);
  if (usersFile && usersFile !== "" && usersFile !== undefined) {
    console.log("Test1");
    return [usersFile, settings.encoding];
  } else {
    console.log("Test2");
    return results;
  }
}

// 调用函数
await userImport(settings, file)
  .then((users) => {
    console.log(users);
  });

关键修正点

  • 移除冗余的变量声明,直接通过await获取响应结果
  • 将auth参数合并到Axios的配置对象中,符合官方参数规范
  • 去掉.then()嵌套,确保userImport函数能正确返回值
  • 使用严格相等运算符!==替代!=,提升代码严谨性

修改后,函数外部即可正确接收到返回的数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 18:21:16