简体   繁体   English

使用 javascript 异步/等待语法时出现奇怪的错误

[英]weird error when using javascript async/await syntax

I was trying to get a random user from the randomuser api.我试图从随机用户 api 中获取随机用户。 The code is from my vue frontend.代码来自我的 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; 
    }

Why the second function doesn't work?为什么第二个 function 不起作用? Thanks.谢谢。

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

You are directly accessing results data ( which might not be assured/yielded yet) instead of waiting for the res.json() to finish processing您正在直接访问结果数据(可能尚未确定/产生),而不是等待res.json()完成处理

EDIT编辑

It is not assured that res.json() will yield any data yet, or there will be any proper response at all.尚不能保证 res.json() 会产生任何数据,或者根本不会有任何适当的响应。 So accessing data is not reasonable yet所以访问数据还不合理

await is getting called on results[0] its not getting called on res.json(); await 被调用 results[0] 它没有被调用 res.json();

To simplify, what you are actually doing is this为简化起见,您实际上在做的是

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

So there are two logical errors in this所以这有两个逻辑错误

await expects a promise in return. await期望得到promise作为回报。 json() returns such a promise, but json().results is just an object (which is even undefined at start). json()返回这样一个 promise,但json().results只是一个object (甚至在开始时未定义)。 Thats why await doesn't work on that structure.这就是为什么await在该结构上不起作用的原因。

Check if res.json().results is not an empty array;检查 res.json().results 是否不是空数组;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM