Home > database >  How to escape this callback hell
How to escape this callback hell

Time:01-20

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.

CodePudding user response:

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');
        });
    );
}

CodePudding user response:

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!

CodePudding user response:

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.

CodePudding user response:

You can probably use async await to get rid of this. Check this link out async await

  •  Tags:  
  • Related