Why Use then()/await Two Times to Get the Data in Fetch API?
The first .then()
gives you access to the Response
object as a promise. However, the Response
object doesn't contain the actual data.
So, why can't you access the data directly after the first .then()
? Why is there a need for a second .then()
?
Let me provide an explanation, as many tutorials often overlook the significance of having two .then()
while teaching Fetch.
There is a good reason behind it. When you make a Fetch call, it returns you a Response
object that has status code, headers and other metadata information. After checking this information, you may not even need the contents, so why waste time parsing it. Data can sometimes be very large, so you save time by not requesting it itself.
Now, once you know the information is valid, then we make another call and fetch the response body (data). The Response
object gives a method to call to decide in what form you need the data.
-
response.text()
– reads the response and returns it as text. -
response.json()
– parses the response as JSON. -
response.blob()
– returns the response as a Blob (binary data with type).
This response body (data) is fetched asynchronously. That is why you require a second then()
.
Get my free, weekly JavaScript tutorials
Want to improve your JavaScript fluency?
Every week, I send a new full-length JavaScript article to thousands of developers. Learn about asynchronous programming, closures, and best practices — as well as general tips for software engineers.
Join today, and level up your JavaScript every Sunday!
Thank you, Taha, for your amazing newsletter. I’m really benefiting from the valuable insights and tips you share.