Fetch & Promise — The What, Why & How
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
urlwe want to access would be a URL for an API.
optionmethod parameter, for example, would include the type of request we are making such as
.thenmethod returns a
Promiseand allows us to get a response and handle data as we wish.
In this blog, we are mainly focusing on
.then so take a look at this code snippet that focuses on the
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.
promise represents the completion of an operation, depending on three possible states:
- a fulfilled state (the operation completed)
- a pending state (the operation has neither been fulfilled nor rejected)
- a rejected state (the operation failed)
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 :
.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
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.