Breaking Down the Fetch API

The fetch() function is one of the tools JavaScript has to access and manipulate data. It’s a global method on the window object. fetch() allows you to make network requests, similar to XMLHttpRequest. XMLHttpRequest used to be more popular but more and more developers are moving away from that method because of the Fetch API’s added flexibility and feature set.

One of the main differences between the two is that the Fetch API uses Promises, which allows for cleaner and simpler code.

A good resource for learning more about Promises is this Google article.

At their most basic, promises are a bit like event listeners except:

▹ A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.

▹ If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.

At its base level, a promise is a process that is checking for a success case or a failed case.

▹ If the case is successful it will run its resolve or fulfilled function.

▹ If the case is failed it will run its reject function.

Let’s look at a basic GET fetch request:

The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response.

So fetch() creates a promise that resolves with a response object. However, this is an HTTP response object, in order to extract the content of the response we need to use the json() method in order to read it.

This returns another promise so we need to add another .then in order to use our data! For every fetch()we need two .then methods.

When we run our fetch(), if any of our .thens were to fail → then the promise would run its reject function.

Most times you will see a .catch at the end of a fetch request. This is just a way to handle this reject. .catch would let us know if any of the lines above fail and console.log the error. catch()could also pass in the error with additional code.

So to recap: if the promise is successful → then the promise would run its resolve function, creating a response object

Which, in the case of our fetch function, is handled by the .then → .then handles the promise returned by the fetch function

And finally, we parse.json() → that works with no errors → then we call .then to handle the data the JSON returns

Software Engineering Student @ Flatiron School