JavaScript Asynchronous Programming with JavaScript Understanding Promises JavaScript Promises Review

Daniel L.
Daniel L.
9,754 Points

Confused about .json() vs .text()

In the final quiz of the Promises section there was this question:

Complete the code by using the method that fetches resources across the network, and the method that parses a Response stream to JSON.

I got the answer correct but I'm just not sure why. I couldn't remember us using .json() anywhere. Why would we use .json() here instead of .responseText?

 fetch ('api.cooldogs.com')
   .then( res => res.json() )
   .then( json => console.log(json) )

1 Answer

Steven Parker
Steven Parker
207,540 Points

The "fetch" result has no "responseText" property, so I assume you meant to say "res.text()"

In that case, the difference is that ".text()" will give you the result in string format, and ".json()" will parse it from JSON and convert it into an object.

But another issue with this example is that the domain "cooldogs.com" seems to no longer be a functioning service and currently belongs to one of those darn domain squatters. You might try the API at dog.ceo as an alternative.