Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ch 2 Async Snippet Returns Undefined #73

Open
armenic opened this issue Nov 22, 2020 · 3 comments
Open

Ch 2 Async Snippet Returns Undefined #73

armenic opened this issue Nov 22, 2020 · 3 comments

Comments

@armenic
Copy link

armenic commented Nov 22, 2020

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();
@brfar
Copy link

brfar commented Dec 9, 2020

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.

@Edy-ux
Copy link

Edy-ux commented Feb 28, 2022

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

@macsir
Copy link

macsir commented Jan 8, 2023

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants