Fetch & Promise — The What, Why & How

So what is fetch? Fetch gives JavaScript the ability to send network requests to a server, load information and allows you to manipulate that information as needed. It is important to know that this can all be done without reloading the page!

The key syntax of a fetch request is the url(the URL we want to access), option (optional parameters such as the method, body, etc.) and .then(which returns a Promise).

  • The url we want to access would be a URL for an API.

In this blog, we are mainly focusing on Promises and .then so take a look at this code snippet that focuses on the url and .then:

fetch('http://example.com/example-items') // here we are accessing the URL we want to gain data from.
.then(response => response.json()) // here we are returning the content of the response and formatting it into json.
.then(data => console.log(data)); // finally we are just logging that response object to the console in our browser.

So let’s dive further into Promises and how they play a role in fetch requests.

A promise represents the completion of an operation, depending on three possible states:

  • a fulfilled state (the operation completed)

Promises provides us a simpler way of executing, composing and managing asynchronous operations.

So let’s look back to our fetch request code snippet and consider what is happening :

fetch('http://example.com/example-items')
.then(response => response.json())
.then(data => console.log(data));

Firstly, when making the initial call to the URL, fetch will not return any data. However it will return a response promise and this means that the URL response we are expecting will get back eventually. It is like it is saying “I promise to give you this information once I have received it”, and so it means that the Promise is in pending state.

If all goes well and we get that URL response, our pending state can change to a fulfilled state otherwise it can be rejected. After this point, our promise becomes settled and cannot change its state again.

Now moving onto the next line of code — .then. We call the json() method on the response to get the body in json format and this operation is also asynchronous. The json() method also returns a Promise and so we create a Promise chain by including the second .then method. In this second .then method, we are simply using console.log() to log the data object we have received, if we have successfully fulfilled the promise of the first .then line.

In this way, Promises are used because it lets asynchronous methods return values like synchronous methods. In other words, an asynchronous method would return a promise to give the value at some point in the future, instead of immediately returning the final value.

Software Engineer 👨🏽‍💻 | Full Stack Web Development 💻 | Smartphone Tech Enthusiast📱