Sitemap

Fetch

2 min readOct 19, 2022

AJAX, also known as “Asynchronous JavaScript and XML”, helped pave the wave for the next evolution of web experiences. Many companies transitioned to AJAX in the 2000s and made their website design more utility with the XMLHttpRequest. Not like before, XMLHttpRequest has the ability to fetch data from a web API and update the DOM without refreshing the page. However, Fetch, the modern successor of the XMLHttpRequest, was made and applied many upgrades to the aging AJAX system.

Get Jeff Chan’s stories in your inbox

Join Medium for free to get updates from this writer.

Unlike AJAX’s XMLHttpRequest, Fetch is a promise-based fetching for requests and responses. This means that Fetch can only fail when there is no connection to the web. Even a wrong URL link inputted into the Fetch function would make it break. The promise is a response object that has the property ‘okay’ that contains a number. Any number 400 or more means there was an error retrieving the data from that URL. The response object is also simplified, making Fetch API calling faster and more efficient than AJAX.

Press enter or click to view image in full size
Example of a Fetch request

The structure of a Fetch request always starts with fetch(‘<URL>’). Then the fetch needs .then statements that tell the computer, after the fetching of the URL, what to do next. These next statements require a callback function within the parameters to be used. We usually need that data from the response so we use response.json() to get the data. We can string the .then statement until the desired outcome.

Another important function that was not in the example above is the await() function. Sometimes problems may arise from the response not being loaded before moving forward. The await() function helps with this by getting the response to completely load before moving on. To use this function, we would wrap the fetch function within the await function like so, await(fetch(…)).

However, there are some limitations to Fetch. It is currently not possible for Fetch to calculate the total amount of data collected/loaded and the total amount of data. Also, all the legacy browsers do not support Fetch. So something like XMLHttpRequest is able to compute the length of work done and the total amount.