Search code examples
javascriptasync-awaites6-promise

Why the first funcion give me results and second one only undefined?


The result should be the same but the second function gives me undefined.

        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

Can it someone please explain to me?


Solution

  • An async function returns always an promise. res.json() aswell

    Instead of resolving the promise like resolve("some data") you need to return to resolve the promise

    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))

    A better approach would be:

    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))