3

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.

ryu
  • 43
  • 3

3 Answers3

1

You can try using async/await. You would add async before the function keyword and add await as needed. See below to see this in action:

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

    renderCountry(data[0]);
    const neighbour = data[0].borders;
    await Promise.all(
        neighbour.map(async country => {
            let response = await fetch(`https://restcountries.com/v2/alpha/${country}`)
            response = await response.json();
            return renderCountry(response, 'neighbour');
        });
    );
}
K.K Designs
  • 688
  • 1
  • 6
  • 22
0

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!

Hakier
  • 505
  • 2
  • 13
  • You [cannot use `forEach` for asynchronous code](https://stackoverflow.com/a/37576787/1048572). – Bergi Jan 19 '22 at 20:41
  • @Bergi I did write "Please note that forEach will run all promises in the same time." – Hakier Jan 19 '22 at 20:42
  • Yes, and that's why it should be avoided. Even if you don't need to wait for anything since there is currently no code after the `forEach()`, it's a footgun waiting to be fired. – Bergi Jan 19 '22 at 20:45
  • I know. I gave a starting point and wrote that he can use a for loop or Bluebird.map for making it better. I didn't want to give a whole fish but encourage him for using a fishing rod – Hakier Jan 19 '22 at 20:49
0

This will do using Async/await

async function getCountryData(country) {
    const response = await fetch(`https://restcountries.com/v2/name/${country}`);
    return await response.json();
}

async function getNeighbourData(country) {
    const response = await fetch(`https://restcountries.com/v2/alpha/${country}`);
    return await response.json();
}

async function getCountryAndNeighbour(country) {
    const data = await getCountryData(country);
    const neighbourCountries = data[1].borders;

    for (const neighbour of neighbourCountries) {
        const response = await getNeighbourData(neighbour);
        console.log(response);
    }
}

Add the necessary validations when checking [0]/[1] in your function.