Fetch API在异步函数中返回未定义的数据

前端开发 2026-07-09

我正在使用JavaScript的 async/await从 API获取数据,但结果返回 undefined

以下是我的代码:

async function getUsers() {
    let response = await fetch("https://jsonplaceholder.typicode.com/users");
    let data = response.json();

    console.log(data);
}

getUsers();

没有得到用户数据,而是得到一个Promise对象或undefined的输出。

我在这里到底哪里出错,如何正确获取JSON数据?

解决方案

你的 data 还不是实际的JSON,因为 response.json() 也会返回一个 Promise。你需要 await 它。

请使用以下代码:

async function getUsers() {
    try {
        const response = await fetch("https://jsonplaceholder.typicode.com/users");

        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }

        const data = await response.json();

        console.log(data);
        return data;
    } catch (error) {
        console.error("Failed to fetch users:", error);
    }
}

getUsers();

另外请记住,如果你想在函数外部使用返回的数据,必须要么 await getUsers() 在另一个异步函数中,或者使用 .then()

getUsers().then(users => {
    console.log(users);
});
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章