为什么此异步函数返回未定义?

时间:2020-09-06 23:03:40

标签: javascript asynchronous

下面的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();

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:2)

您也正在等待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();