为啥这个异步函数返回未定义? [复制]

Posted

技术标签:

【中文标题】为啥这个异步函数返回未定义? [复制]【英文标题】:Why does this asynchronous function return undefined? [duplicate]为什么这个异步函数返回未定义? [复制] 【发布时间】:2020-12-25 09:44:50 【问题描述】:

以下 javascript 代码的目的是从 Random User Generator 获取数据,并将 JSON 结果打印到控制台。声明后调用函数时,返回“未定义”。

为什么这个异步函数返回为 undefined 而不是将 fetch 方法的结果打印到控制台?

const getRandomUser = async () => 
  try 
    let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
    let  results  = res.json();
    console.log(results);
   catch (error) 
    console.error(error);
  
;

getRandomUser();

【问题讨论】:

要补充答案,您可以参考here 并注意json() 的返回值是Promise 【参考方案1】:

您也有 await res.json(),所以在您的情况下,它最终应该是这样的:

const getRandomUser = async () => 
  try 
    let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
    let  results  = await res.json(); // Notice the await
    console.log(results);
   catch (error) 
    console.error(error);
  
;

getRandomUser();

【讨论】:

【参考方案2】:

.json 返回一个 promise 对象,需要等待才能取回该值。这返回了

[
  
    "gender": "male",
    "name": 
      "title": "Mr",
      "first": "Andrew",
      "last": "Alvarez"
    ,
    "location": 
      "street": 
        "number": 6490,
        "name": "E North St"
      ,
      "city": "El Cajon",
      "state": "Hawaii",
      "country": "United States",
      "postcode": 78991,
      "coordinates": 
        "latitude": "-66.7376",
        "longitude": "-3.0261"
      ,
      "timezone": 
        "offset": "-1:00",
        "description": "Azores, Cape Verde Islands"
      
    ,
    "email": "andrew.alvarez@example.com",
    "login": 
      "uuid": "006a343c-98de-45f0-ba0f-fb053be9efb2",
      "username": "angrywolf977",
      "password": "nobody",
      "salt": "JH14v7c8",
      "md5": "8c69fb8a8d65dbbf3cbdb71679b44c9e",
      "sha1": "b03b94155eff0dac5b733d7398a68b2e3f0513b1",
      "sha256": "fb26ce1e4cc7f067c6da9208454a91bda94fc3403119ebfa491a9620ff25de53"
    ,
    "dob": 
      "date": "1982-06-30T11:22:22.724Z",
      "age": 38
    ,
    "registered": 
      "date": "2002-09-12T21:36:16.737Z",
      "age": 18
    ,
    "phone": "(278)-599-6197",
    "cell": "(842)-913-4573",
    "id": 
      "name": "SSN",
      "value": "639-63-2310"
    ,
    "picture": 
      "large": "https://randomuser.me/api/portraits/men/36.jpg",
      "medium": "https://randomuser.me/api/portraits/med/men/36.jpg",
      "thumbnail": "https://randomuser.me/api/portraits/thumb/men/36.jpg"
    ,
    "nat": "US"
  
]

const getRandomUser = async () => 
  try 
    let res = await fetch("https://api.randomuser.me/?nat=US&results=1");
    let  results  = await res.json();
    console.log(results);
   catch (error) 
    console.error(error);
  
;

getRandomUser();

【讨论】:

以上是关于为啥这个异步函数返回未定义? [复制]的主要内容,如果未能解决你的问题,请参考以下文章

为啥运行时返回未定义? [复制]

为啥我的 .parentNode 返回未定义? [复制]

为啥 array[array.length] 返回未定义? [复制]

异步函数总是返回未定义

返回未定义的异步函数

如果未返回,reduce 函数的累加器未定义。为啥它会这样?