为什么第一个函数给我结果,而第二个函数只有我不确定?

时间:2020-11-03 12:19:11

标签: javascript async-await es6-promise

结果应该相同,但是第二个函数给了我未定义的信息。

        fetch("https://api.randomuser.me/?nat=US&results=1").then(res => res.json()).then(json => json.results).then(console.log).catch(console.error); // {user: xyz, ... }


   const getFakePerson = 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);
     }; 
   } 
    getFakePerson(); // Undefined

有人可以向我解释吗?

2 个答案:

答案 0 :(得分:2)

一个异步函数总是返回一个承诺。还有res.json()

您需要resolve("some data")来解决承诺,而不是像return那样解决承诺

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

更好的方法是:

const getFakePerson = async () => {
   return fetch("https://api.randomuser.me/?nat=US&results=1")
            .then(res => res.json())
            .then(res => res.results)
}

getFakePerson()
  .then(res => console.log(res))

答案 1 :(得分:0)

您可以像这样工作

fetch("https://api.randomuser.me/?nat=US&results=1").then(res => res.json()).then(json => json.results).then(console.log).catch(console.error); // 


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

相关问题