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

为何使用await的Axios Get请求async函数调用后仍返回Promise?

Why getNewUser() logs a Promise instead of the JSON data

Let's break this down simply: async functions always return a Promise, no matter what value you return inside them. Even if you return a plain object or primitive, JavaScript automatically wraps it in a resolved Promise.

In your code, when you call console.log(getNewUser()), you’re logging the Promise object immediately—before it has a chance to resolve and fetch the actual API data. The console.log(data) inside the function works because that line runs after the await has waited for the API call to finish, so data is the actual JSON response body.


How to fix it

There are two straightforward ways to access the resolved JSON data:

1. Use .then() to handle the Promise resolution

Since getNewUser() returns a Promise, chain a .then() method to it to access the resolved value once it’s ready:

const getNewUser = async () => { 
  const data = await api.get("/").then((data) => data.data.results[0]); 
  console.log(data); // Logs the actual JSON data
  return data; 
}; 

// Chain .then() to get the resolved user data
getNewUser().then(userData => {
  console.log(userData); // Now logs the JSON object, not a Promise
});

2. Use await inside another async function

You can only use await within an async function, so wrap your call in either a named async function or an immediately-invoked async function expression (IIFE):

Option A: Named async function

const getNewUser = async () => { 
  const data = await api.get("/").then((data) => data.data.results[0]); 
  console.log(data); 
  return data; 
}; 

async function logNewUser() {
  const userData = await getNewUser();
  console.log(userData); // Logs the JSON object
}

logNewUser();

Option B: IIFE (immediately run the code)

const getNewUser = async () => { 
  const data = await api.get("/").then((data) => data.data.results[0]); 
  console.log(data); 
  return data; 
}; 

// Immediately invoke an async function to use await
(async () => {
  const userData = await getNewUser();
  console.log(userData); // Logs the JSON object
})();

Quick cleanup tip

You can simplify your getNewUser function to avoid mixing await and .then()—it works as-is, but sticking to one style makes the code cleaner:

// Using only await (more consistent and readable)
const getNewUser = async () => { 
  const response = await api.get("/");
  const data = response.data.results[0];
  console.log(data); 
  return data; 
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 17:47:49