Ch 2 Async Snippet Returns Undefined
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();
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.
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();`
As the fetch returns a promise from the first await, then the second await is natural to add for resolving into value.