Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSteve Fau
5,622 PointsWhy do we need to await peopleResponse.json() ?
From the video:
const peopleResponse = await fetch(url)
const peopleJSON = await peopleResponse.json()
We need to await fetch(url)
, because it returns a Promise, but why do we also need to await peopleResponse.json()
?
1 Answer
Dane Parchment
Treehouse Moderator 11,077 PointsYou are correct in your line of thinking with await
effectively replacing then()
in a way.
Now the reason we do the await on the peopleResponse.json()
is because the .json() method is actually an async promise-based method.
See here:
response.json().then((data) => {console.log(data);})
So we use await
their too.
Remember, await
pauses the code at execution at that line of code until the promise we are awaiting fulfils, then it returns the result and moves on to the next line. Which is why we pause the code at the response.json()
as well!
Steve Fau
5,622 PointsThanks Dane, that makes sense :)
Interestingly enough, if I remove the await keyword and click through the PromiseΒ {<pending>}
in the console, the data is still available there under [[PromiseResult]]
.
Seems like synchronous behaviour since I'm not waiting for anything.
Steve Fau
5,622 PointsSteve Fau
5,622 PointsIs it because we're working with the Promise all the way and the
await
keyword essentially replaces what we would do with.then()
?