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

470
Visualizações
How do I wait for a promise to finish inside a loop? (without using async-await)

The below code waits only for the 1st iteration of the for loop. If I use async-await, it works fine. So where am I going wrong here?

function wait(milliseconds) {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

function countDown(count) {
  for (let i = count; i > 0; i--) {
    wait(1000)
      .then(() => console.log(i))
      .catch((error) => console.log(error));
  }
}

countDown(5);
about 4 years ago · Santiago Gelvez
2 Respostas
Responde à pergunta

0

Because the Promise will run the "then" statement when it done its task. And if you use the loop like that, the Promise for i=4 will immediately execute after i=5 executed. This will make the output just only wait for the first one.

The solution for this is run the Promise (i=4) after the Promise (i=5) done using recursive function.

function wait(milliseconds) {
    return new Promise(resolve => setTimeout(resolve, milliseconds))
}

function countDown(count) {
    if (count === 0) return;
    wait(1000)
        .then(() => {
            console.log(count)
            countDown(count - 1)
        })
        .catch((error) => console.log(error));
}

countDown(5);
about 4 years ago · Santiago Gelvez Relatório

0

Execution doesn't stop when you call then on a Promise like it does when you use await. On the first loop a Promise is created whose then method will execute in one second, but the function continues looping because execution hasn't stopped. At the end of the loop you have five Promise objects that have all been created consecutively with no pauses in between, so their one-second timeouts all execute very close to one another.

Here's the await method with a comment calling out where execution stops.

function wait(milliseconds) {
    return new Promise(resolve => setTimeout(resolve, milliseconds));
}

async function countDown(count) {
    for (let i = count; i > 0; i--) {
        await wait(1000); // Execution stops here for one second before continuing
        console.log(i);
    }
}

countDown(5);

Here's something closer to Phúc Đỗ Vương's answer with a comment calling out where execution doesn't stop.

function wait(milliseconds) {
    return new Promise(resolve => setTimeout(resolve, milliseconds));
}

function countDown(count) {
    if (count === 0) {
        return;
    }
    
    wait(1000).then(() => {
        // This code, including the next call to countDown, will execute in one second
        console.log(count);
        countDown(count - 1);
    });

    // The current call to countDown finishes before the next call begins
}

countDown(5);
about 4 years ago · Santiago Gelvez 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