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 trial

JavaScript Asynchronous Programming with JavaScript Exploring Async/Await Convert Promise Handling to Async/Await

Why 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() ?

Is it because we're working with the Promise all the way and the await keyword essentially replaces what we would do with .then() ?

1 Answer

Dane Parchment
MOD
Dane Parchment
Treehouse Moderator 11,075 Points

You 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!

Thanks 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.