如何从async函数返回值?解决调用后返回Promise<pending>问题
Hey there! I totally get why this is confusing at first—let's break down what's happening and how to fix it.
First off, the key thing to remember: any async function automatically wraps its return value in a Promise, no matter what you actually return. When you call getData() and immediately console.log it, you're just logging the pending Promise object before the axios request has finished. The async operation (the HTTP call) is still running in the background, so the Promise hasn't resolved to your actual data yet.
Here are two straightforward ways to get the actual data you want:
方法1:使用.then()处理Promise结果
Since getData() returns a Promise, you can use the .then() method to wait for it to resolve and access the data. Don't forget to add .catch() to handle potential errors like network issues!
const axios = require('axios'); async function getData() { const data = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; } // 用.then()获取结果 getData() .then(result => { console.log(result); // 这里就是你要的实际响应数据 }) .catch(error => { console.error('请求出错啦:', error); // 处理请求失败的情况 });
方法2:在async函数中使用await(配合IIFE或顶层await)
await lets you pause execution until the Promise resolves, but it can only be used inside an async function. If you're working in the top-level scope (like a Node.js script), you have two options:
选项A:立即执行的async函数表达式(IIFE)
This is a safe, widely compatible way to wrap your await call:
const axios = require('axios'); async function getData() { const data = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; } // 用IIFE创建一个async环境 (async () => { try { const result = await getData(); console.log(result); } catch (error) { console.error('请求出错啦:', error); } })();
选项B:顶层await(环境支持时)
If you're using Node.js 14.8+ (with ES modules) or modern browsers, you can use await directly at the top level without wrapping it in a function:
const axios = require('axios'); async function getData() { const data = await axios.get('https://jsonplaceholder.typicode.com/posts'); return data; } // 顶层await(需环境支持) const result = await getData(); console.log(result);
重要提醒
Always handle errors! Whether you use .catch() or try/catch, ignoring errors can lead to uncaught Promise rejection errors that crash your app.
内容的提问来源于stack exchange,提问作者King Rayhan

