![]() |
VOOZH | about |
For long XMLHttpRequest is being used by web developer's trusted "amigo". XMLHttpRequest has enabled ajax and a whole new kind of interactive exposure.
However, it is being slowly succeeded by the Fetch API. These both deliver the same work i.e. fetching data asynchronously from a different network, but the Fetch API is Promise based. This provides a more cleaner and more concise syntax.
The Fetch API provides the fetch() method defined on a window object. This is used to perform requests. This method returns a Promise which can be further used to retrieve response of the request.
Basic Syntax:
fetch(url) //call the fetch function passing the url of the API as a parameter
.then(function(){
//code for handling data from API
});
.catch(function(){
//code when the server returns any error
});
NOTE: By default, fetch() will not send or receive any cookies from the server, resulting in unauthenticated requests.
Below are list of methods which can be used when we get a response on what we want to do with the information:
Request:
A Request object represents the request part of a fetch call. By passing fetch a Request you can make advanced and customized requests:
LOADING JSON
We cannot block the user interface waiting until the request completes. That is why fetch() method returns a Promise. A promise is actually an object which represents a future result. The then() method is used to wait for the response from the server-side and log it to the console.
Below code snippet explains the above logic:
Async...await
This provides a more concise way to process Promises. Its functionality is that we can mark a function as async, then wait for the promise to finish with the await, and access the result as a normal object.
Simple example demonstrating how async...await can be used:
HANDLING ERRORS:
What if we ask the server for a non-existing resource that requires permissions/authorization? With fetch(), we can handle application-level errors like 404 responses.
Although Fetch API is superseding XMLHttpRequest still a beginner needs to learn XMLHttpRequest to make more effective use of Fetch API.
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API