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

209
Visualizações
Why doesn't this recursive solution work with asynchronous functions in Javascript, but works fine iteratively?

Been coding in JavaScript for about a year but I have this weird error/bug I have found a work around solution, but am curious on an explanation as to why.

So I have an asynchronous function receiving weather data from an API getWeatherStats() It returns a promise which is opened with the .then notation in another function called getCoordinates(). I simplified the weatherParser() function to show that if I make the solution recursive, it returns undefined, but if done iteratively it works fine.

getWeatherStats(city).then((data) => {
  console.log(data)
  var i = 0;
  var done = weatherParser(data, i);
  console.log(done); //returns undefined if done recursively, is fine if done iteratively
})


async function getWeatherStats(city) {
  var url = `http://api.openweathermap.org/data/2.5/forecast?q=${city}&appid=${weatherKey}`;


  let response = await fetch(url);
  let data = await response.json();
  var i = 0;
  return new Promise(resolve => {
    resolve(data);
  }, 2000);

Here's the recursive solution that returns null

function weatherParser(data, i, widgetHolder, date = null) {
  if (i > 20) return 'hello'
  i++;
  weatherParser(data, i, widgetHolder, date)

Iterative solution:

function weatherParser(data, i, widgetHolder, date = null) {
  for (var i = 0; i < 20; i++) {

  }
  return 'hello'
about 4 years ago · Juan Pablo Isaza
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