Skip to main content

Command Palette

Search for a command to run...

[JavaScript] Asynchronous JavaScript: Promises, Async/Await, and AJAX - Callback Hell

Published
•View as Markdown
const renderCountry = function (data, className = '') {
  const html = `
  <article class="country ${className}">
    <img class="country__img" src="${data.flag}" />
    <div class="country__data">
        <h3 class="country__name">${data.name}</h3>
        <h4 class="country__region">${data.region}</h4>
        <p class="country__row"><span>👫</span>${(
          +data.population / 1000000
        ).toFixed(1)} people</p>
        <p class="country__row"><span>🗣️</span>${data.languages[0].name}</p>
        <p class="country__row"><span>💰</span>${data.currencies[0].name}</p>
        </div>
    </article>
    `;
  countriesContainer.insertAdjacentHTML('beforeend', html);
  countriesContainer.style.opacity = 1;
};

const getCountryAndNeighbor = function (country) {
  // AJAX country 1
  const request = new XMLHttpRequest();
  request.open('GET', `https://restcountries.com/v2/name/${country}`);
  request.send();

  request.addEventListener('load', function () {
    const [data] = JSON.parse(this.responseText);
    console.log(data);

    //render country (1)
    renderCountry(data);

    // Get neighbor country (2)
    const [neighbor] = data.borders;

    if (!neighbor) return;

    // AJAX country 2
    const request2 = new XMLHttpRequest();
    request2.open('GET', `https://restcountries.com/v2/alpha/${neighbor}`);
    request2.send();

    request2.addEventListener('load', function () {
      const data2 = JSON.parse(this.responseText); // no array return. no needs destructuring
      console.log(data2);

      renderCountry(data2, 'neighbor');
    });
  });
};

// getCountryAndNeighbor('portugal');
getCountryAndNeighbor('usa');

callback hell 1.PNG

getCountryAndNeighbor('portugal');
// getCountryAndNeighbor('usa');

callback hell 2.PNG

  • Callback Hell structure
    // callback hell
    setTimeout(() => {
    console.log('1 second passed');
      setTimeout(() => {
        console.log('2 seconds passed');
        setTimeout(() => {
          console.log('3 seconds passed');
          setTimeout(() => {
            console.log('4 seconds passed');
            setTimeout(() => {
              console.log('5 seconds passed');
            }, 1000);
          }, 1000);
        }, 1000);
      }, 1000);
    }, 1000);
    

callback hell 3.PNG

Callback Hell can cause lots of issues when it has longer and longer codes. (ex. difficult to debug, difficult to understand codes, etc) It is not a good practice. So, use Promises in ES6.

JavaScript

Part 1 of 50

More from this blog

Jayden's Blog

166 posts