Dealing with JS’s asynchronous HTTP requests
As a human being, you’re multithreaded. You can type with multiple fingers, you can drive and hold a conversation at the same time. The only blocking function we have to deal with is sneezing, where all current activity must be suspended for the duration of the sneeze. That’s pretty annoying, especially when you’re driving and trying to hold a conversation. You don’t want to write code that’s sneezy.
Promises prevent developers from writing ‘sneezy’ code which is really important for fetching API’s its main purpose is to make requests for assets or data.
Back to Fetch
fetch() method returns a
Promise that resolves the
Response from the
Request to show the status (successful or not).
So in short, we first define the path (Fetch), second, request data from the server (Request), thirdly define the content type (Body), and lastly, we access the data (Response).
I recommend using the catch method when writing your code. The catch method is a callback method that will intercept any errors occurring during the execution of the request.
Working With an Example
So now let’s talk through an example. For this example, we’ll use the fabulous JSONplaceholder site to fetch posts data. After creating your index.html file and adding the HTML skeleton you will need to create a button which I named Get API Data.
Once finished you will need to add an event listener. An event listener basically attaches an event handler to the specified element. In this case, the event listener will be looking for the id with the text “getPosts” and once it’s clicked on will call the function #getPosts.
Then you will need to create your function which will look similar to the function below. So for every
fetch() whose data you want to show or manipulate you will need at least two
then() methods: the first to return the response method that retrieves your data, and the second then to actually work with the data.
And just like that, you have created a button which when clicked on will return a post!
Go Forth and Fetch
Bam! There you have it, the very basics of