Then What? Promises Promises
What happens after the fetch request is complete
Last week, the sub-title of my Fetch! blog post was “Sending a request to the back end server to be processed and then returning the result.” This blog post will go into further detail about the latter part “…then returning the result.” The word then will figure prominently because it’s actually a method that handles what is returned from a fetch request. But first, let’s focus on what is returned, a promise.
Cue music Promises Promises.
So what exactly is a promise? A promise is like a placeholder, promising to hold your place in line until after the request has completed or loaded and then resolving whatever is returned. In other words:
Promises simplify deferred and asynchronous computations. A promise represents an operation that hasn’t completed yet. — https://web.dev/promises
A fetch request returns a promise whether the request was successful or not. The act of calling fetch returns a promise allowing the request to complete asynchronously. The data that is returned can be in the format of JSON or XML. We use the then( ) method to handle the return value of the promise which resolves into a Response object. This Response object contains the data that was returned. Use a Response object method, either json( ) or text( ), to extract the data from the Response object.
.then(resp => resp.json( ))
My Fetch! blog post used a theme of dog images to illustrate how to write a simple fetch request.
I’ll build on that example to illustrate how to use the then( ) method to capture the result of the fetch request. To do this, you simply place the then( ) method after the fetch request.
The fetch request will go to the passed in URL address. Then returns the result by passing it in to the then( ) method which I’ve indicated as response. Then use the json( ) method to extract the data in the JSON format.
Now what do I do with this formatted JSON data? To capture it, I simply tack on another then( ) method where it’s passed in and now I refer to it as dogImagesData:
I used console.log to check the result in the console. To manipulate the data, I would replace the console.log with a different method call to achieve the result I desired like to display the dog images in the browser. Once you have the extracted data, you can call methods to manipulate it to serve your application purposes.