Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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');
        });
    );
}
about 4 years ago · Juan Pablo Isaza Report

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.

about 4 years ago · Juan Pablo Isaza Report

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!

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!