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

Steve Fau
Steve Fau
5,621 Points

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

Steve Fau
Steve Fau
5,621 Points

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 10,232 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!

Steve Fau
Steve Fau
5,621 Points

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.