首页 > 解决方案 > 使用 javascript async/await 语法时出现奇怪的错误

问题描述

我试图从 randomuser api 中获取一个随机用户。代码来自我的 vue 前端。

// api response
{ info: { // ommited }, results: [ {//random user data} ] }

// this works
async get_random_user() {
        const url = "https://randomuser.me/api/";
        const res = await fetch(url);
        const json_data = await res.json();
        const result = json_data.results[0];
        return result; 
    }

// this throws Uncaught (in promise) TypeError: Cannot read property '0' of undefined
async get_random_user() {
        const url = "https://randomuser.me/api/";
        const res = await fetch(url);
        const result = await res.json().results[0];
        return result; 
    }

为什么第二个功能不起作用?谢谢。

标签: javascriptvue.jsasync-await

解决方案


const result = await res.json().results[0];

您正在直接访问结果数据(可能尚未确定/产生),而不是等待 res.json()完成处理

编辑

尚不能保证 res.json() 会产生任何数据,或者根本不会有任何适当的响应。所以访问数据还不合理

await 被调用 results[0] 它没有被调用 res.json();

为简化起见,您实际上在做的是

results = res.json();
const result = await results[0];

所以这有两个逻辑错误


推荐阅读