【发布时间】: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