Callback Hell

by sbjami

HTML

<body>
  <h1>
    Callback Hell
  </h1>
  <button id="fetchBtn">
    Fetch data
  </button>
  <p id="userData">
    User data goes here
  </p>
  <hr>
  <p id="postsData">
    Posts data goes here
  </p>
</body>

CSS

button {
  color: red;
}

JavaScript

const baseUrl = "https://jsonplaceholder.typicode.com";
const postsUrl = `${baseUrl}/posts`;
const usersUrl = `${baseUrl}/users`;
const userId = 1;

document.getElementById("fetchBtn").addEventListener("click", () => {
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      if (xhr.status == 200) {
        document.getElementById("userData").innerText = xhr.responseText;
        const xhr2 = new XMLHttpRequest();
        xhr2.onreadystatechange = function() {
          if (xhr2.readyState == 4) {
            if (xhr2.status == 200) {
              document.getElementById("postsData").innerText = xhr2.responseText;
            } else {
              console.error("Unsuccessful transfer (error code: " + xhr.statusText + ")");
            }
          }
        }

        xhr2.open("GET", `${postsUrl}?userId=${userId}`, true)
        xhr2.send();
      } else {
        console.error("Unsuccessful transfer (error code: " + xhr2.statusText + ")");
      }
    }
  }

  xhr.open("GET", `${usersUrl}/${userId}`, true)
  xhr.send();
})