Fetching the data from the server and populating it into the DOM is the primary feature of any app. Let's stroll with me how it started with Web APIs:
- ActiveXObject - Introduced in 1996. It was devised by Microsoft for its specific products only like Internet Explorer and for Flash Shockwave applications (downgraded).
- XMLHttpRequest - Introduced in year 2000. It was widely used to fetch data from the server without refreshing the page as AJAX (Asynchronous JavaScript XML) Programming.
- fetch API - Available since 2012 in ES6 feature. This is the latest interface that returns a Promise, by which we can handle results and even catch any error encountered. Moreover, its code is very slick.
Let's go through some examples:
XMLHttpRequest - aka XHR
return new Promise((resolve, reject) => {****
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.open("GET", "https://jsonplaceholder.typicode.com/posts");
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState === 4 && xmlHttpReq.status === 200) {
resolve(xmlHttpReq.responseText);
} else if (xmlHttpReq.readyState === 4 && xmlHttpReq.status !== 200) {
reject("Something went wrong ," + xmlHttpReq.status + " !");
}
};
xmlHttpReq.send();
});
Fetch API
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((json) => console.log(json))
.catch(error => console.error('Error:', error));
Conclusion:
These days, as developers, we care more about developer experience along with user experience, so to refine the fetch API code, It's best practice to use async-await (introduced in ES2017 aka ES8) to avoid promise chaining.
async function getPosts() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts');
return await response.json()
} catch {
console.log('Something went wrong')
}
}