Behind the Scenes of Fetch() in Javascript

Behind the Scenes of Fetch() in Javascript

As you begin to make more complex websites with Javascript, you will have to interact with the server. You might want to make some changes on your website based on your processing at the server and there's one technique called Ajax that really might come in handy which helps us do that without reloading the page in order to have a good user experience.

Ajax, also called Asynchronous Javascript and XML, helps us to refresh sections of the page without reloading the page. For example, if you are looking at a sports website that shows live scores, it updates section of the score at a set time interval after interacting with the server. Similarly, you might notice a new email update in your gmail account at the top without the reload of a page.

Callback function using XMLHttpRequest()

In order to implement this, we create a Javascript object of XMLHttpRequest.

    var obj = new XMLHttpRequest();

Once you have the object, the first thing you have to do is define an onreadystatechange behavior. Onreadystatechange is really just a way to describe the steps that are happening when you visit a page. Different state changes that might take place when you're visiting a site are:

  • the request hasn't been initiated
  • sending the request
  • request is received
  • request is on its way back
  • the request is complete

Then we define this function that that will be called when HTTP request has been completed. It typically defines what is expected to change on the website.

As we have seen above, the readyState property changes from 0 (request not initiated) to finally 4(request is completed). The status property in case of success should be 200. In any other case like 404, we cannot send the valid response to the client.

Then we just make asynchronous request using open() method to define the request and send() method to actually send it.

So, below is how we you can a javascript function for preparing, opening and sending the ajax request.

function ajax_request(args){

    var obj = new XMLHttpRequest();
    // Callback function if request is complete
    obj.onreadystatechange = function() {
        if (obj.readyState == 4 && obj.status == 200) {
            // do something to the element
        }
        obj.open("GET",'enter the URL here you want to open to insert', true);
        obj.send();
    };
};

That's it! You have created an ajax request using callback function. But if you have observed in this example, its a lot of work to do, and this gets very lengthy and hard to maintain on multiple callbacks for a particular event. This is why, this is not the most common way to handle asynchronous calls. Now, lets look at what concept of 'promises' promise us.

Using Fetch

The second way is using fetch() function. Fetch carries out the above operations in a much cleaner way using Promises. The responses of fetch() are sent in Promises. Promises indicate success or error on rejection of an ajax call. If rejected, we can handle the errors using catch() method.

function dofetch(textinput) {
    fetch(apiURL)
    .then(response => response.json())
    .then(data => // do something to the element)
    .catch(errorHandler)
};

In the above example, the URL for API call is sent using fetch, the response received from Promise if successful, sends the data to second call of then(); if not successful, it is passed on to the errorHandler() function in catch().

Conclusion

I hope you enjoyed this short blog on how the asynchronous calls takes place when we use Fetch(). It is good to know what happens in network call to API in detail, even though using fetch() is more common and prominent because it supports making multiple calls without making things messy.