Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,020 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.