fetch 后得到什么以及如何处理

evg*_*enn -1 javascript fetch

请求后,我在正文中得到响应,它看起来像 [{...}]。在我的浏览器控制台中,它被视为数组。但 console.log(users[0]) 被解释为未定义。为什么我无法获取用户对象的第一个元素?

    async function getUsers() {
    const response = await fetch("/api/users");
    const users = await response.json();
    return users;
}

let users = getUsers();
console.log(users[0]);
console.log(users);
Run Code Online (Sandbox Code Playgroud)

小智 5

fetch 后得到的是一个承诺

您可以使用 .then 异步处理它

getUsers().then((users) => {
    console.log(users[0]); //returns the user with in the first index
    console.log(users); // returns all users
});
Run Code Online (Sandbox Code Playgroud)