Unlocking the Mysteries of the Fetch API: Beyond the Basics

Vedansh MishraVedansh Mishra
2 min read

Before starting, I have a question. Let's say you get a 404 error (file not found) while fetching a request. Where will the data get stored: in resolve or reject? Stay connected with the article to find the answer by the end.

You must have been using fetch to make network requests in your web applications. Do you understand how it works internally? If not, by the end of this article, you'll gain new insights into fetch that will change your perspective on this essential web API.

Here's a basic example of how you have been using the fetch API.

Now let's say we have a code as shown below.

The first output that comes to mind is:

But the correct output is:

How? We have learned that code runs sequentially in JavaScript, yet here the last console log is being printed before the first two. Ideally, the first console log should have been printed after a waiting time of 1 second, followed by the second console log, and then the third.
The reason for this is that a special microtask/priority queue exists specifically for the fetch API so that fetch doesn't have to wait in the regular queue. The diagram below provides a good explanation of the concept I just explained.


Where do the errors like 404 get stored?

I asked a question at the beginning: where do errors like 404, 502, 504, etc get stored, in resolve or reject? Well, the answer is resolve. Here's why.

If an error like 404 occurs, it means the network request was successful. Even though 404 is an error, it only occurs when the network request is successful, so it will be stored in resolve instead of reject. If there had been an error due to a network request failure, then the error would have been stored in reject.

Here, 'on Fulfilled' and 'on Rejection' are arrays that store resolve and reject values, respectively. We are not allowed to push values directly into these arrays. Ultimately, when the network request is completed, the data is fulfilled by one of them, which is then eventually transmitted as a response. And that's how you get a response from a fetch request.


My primary goal in writing this blog post is to both share my knowledge and learn more about the topic. If you have any suggestions for improving my writing, please feel free to reach out to me on Twitter. Additionally, I share a lot more content there, so be sure to check it out.

0
Subscribe to my newsletter

Read articles from Vedansh Mishra directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vedansh Mishra
Vedansh Mishra

I love sharing my knowledge through articles and enjoy learning from others' ideas and writings.