Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

182
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda