Skip to main content

Command Palette

Search for a command to run...

Inception of retrieving data from the server

Published
2 min read
Inception of retrieving data from the server
N

I am a self taught web developer owning experience of 12+ years in web development field.

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:

  1. ActiveXObject - Introduced in 1996. It was devised by Microsoft for its specific products only like Internet Explorer and for Flash Shockwave applications (downgraded).
  2. 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.
  3. 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')
 }
}
R

Nice to looking at searching file explorer windows 10 thanks for this

More from this blog

W

Web Chronicles

12 posts

I'm a Senior Full Stack Developer with 10+ years of experience. I strive to be a humble team player and be approachable to receive and give feedback.