javascript - 使用 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;
}
为什么第二个功能不起作用?谢谢。
解决方案
const result = await res.json().results[0];
您正在直接访问结果数据(可能尚未确定/产生),而不是等待 res.json()完成处理
编辑
尚不能保证 res.json() 会产生任何数据,或者根本不会有任何适当的响应。所以访问数据还不合理
await 被调用 results[0] 它没有被调用 res.json();
为简化起见,您实际上在做的是
results = res.json();
const result = await results[0];
所以这有两个逻辑错误
推荐阅读
- java - 请帮助在 Java 代码中阅读此抽象数据类型
- parallel-processing - 在并行循环中,如果多个线程的条件为真而不是第一次遇到
- ios - 用作分页加载器时的 Gif,有时不显示在图像视图中
- c# - C# 中的自定义自动属性
- export - 如何使用 IronPython 脚本仅导出 Spotfire Selected 列?
- html - 隐藏在粘性导航栏后面的文本 (HTML/CSS)
- angular - Primeng P-calendar issue (UTC)
- php - Slim 框架给出了一个令人困惑的未捕获类型错误
- php - MySQL数据库的PHP编辑表单
- c++ - grpc builder.BuildAndStart() 挂在 aarch64 但不是 x86_64