Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to escape this callback hell

I’m currently trying to fetch data from public API about a country and its neighboring countries to render on my html.
renderCountry( ) is a function to implement on my html with the data I will receive.
I also excluded some unnecessary codes, which I believe is not major in this particular case.

This is how I fetch data:

const getCountryAndNeighbour = function(country) {
    fetch(`https://restcountries.com/v2/name/${country}`)
        .then(response => response.json())
        .then(data => {
            renderCountry(data[0]);
            const neighbour = data[0].borders;    
            neighbour.forEach(country => {
                fetch(`https://restcountries.com/v2/alpha/${country}`)
                .then(response => response.json())
                .then(data => renderCountry(data, `neighbour`))
            });
        })
}

Here, you will see callback hell architecture. Any idea for escape from that?
Thanks in advance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can rewrite it using async/await

eg.

const getCountryAndNeighbour = async country => {
  const response = await fetch(`https://restcountries.com/v2/name/${country}`);
  const data = await response.json();

  renderCountry(data[0]);

  const neighbour = data[0].borders;
  neighbour.forEach(async country => {
    const response = await fetch(`https://restcountries.com/v2/alpha/${country}`)
    const data = await response.json();

    renderCountry(data, `neighbour`);
  });
};

Please note that forEach will run all promises in the same time.

If you want to run one by one you should use eg. for loop or some util like Bluebird.map which allows you to specify a concurrency

Good luck!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading