learning-react icon indicating copy to clipboard operation
learning-react copied to clipboard

Ch 2 Async Snippet Returns Undefined

Open armenic opened this issue 4 years ago • 3 comments

Dear Authors,

The code snippet in Ch 2 returns undefined:

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

I believe the solution is to add await before the res.json():

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

getFakePerson();

armenic avatar Nov 22 '20 16:11 armenic

Thank you! I attached .then(res => res.json()) to the fetch() and deleted the let { results } = res.json() but your solution looks much much nicer.

brfar avatar Dec 09 '20 23:12 brfar

It´s work for me

`const getFakePerson = 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); } };

getFakePerson();`

Edy-ux avatar Feb 28 '22 01:02 Edy-ux

As the fetch returns a promise from the first await, then the second await is natural to add for resolving into value.

macsir avatar Jan 08 '23 07:01 macsir