【问题标题】:weird error when using javascript async/await syntax使用 javascript async/await 语法时出现奇怪的错误
【发布时间】:2021-04-28 16:02:08
【问题描述】:

我试图从 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; 
    }

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

【问题讨论】:

  • 如果将 (await res.json) 括在括号中会怎样?

标签: javascript vue.js async-await


【解决方案1】:
const result = await res.json().results[0];

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

编辑

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

正在调用结果 [0] 它没有被调用 res.json();

为了简化,你实际上在做的是这个

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

所以这里有两个逻辑错误

【讨论】:

  • 我现在知道了。我在 js async/await 语法中迈出了第一步 :)
【解决方案2】:

await 期望得到promise 作为回报。 json() 返回这样一个承诺,但 json().results 只是一个 object (甚至在开始时未定义)。这就是为什么await 不适用于该结构的原因。

【讨论】:

    【解决方案3】:

    检查 res.json().results 是否不是空数组;

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

    【讨论】:

    • 谢谢,我现在知道了。 const result = (await res.json()).results.[0]; 确实有效。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-09
    • 1970-01-01
    相关资源
    最近更新 更多