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

76
Visualizações
How to count number using promise

I want to counter some number using promise that the result is 1,2,3,done and I have coded it like this

const state = true

const count = new Promise((resolve, reject) => {
  if (state) {
    resolve("counter work")
    for (let i = 1; i <= 3; i++) {
      setTimeout(() => {
        console.log(i);
      }, 1000);
    }
    console.log("done");
  } else {
    reject("counter not work")
  }
})
count
  .then((response) => console.log("success", response))
  .catch((response) => console.log("failed", response));

and the result is : done,1,2,3 but i want the result 1,2,3,done

can anybody tell why my code have result like that and how the code should it is

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The early resolve aside, the reason for "done" being logged first is that you're calling setTimeout in a loop. setTimeout doesn't block execution, it queues a callback to be run after some time and returns immediately. So you're just creating three Timeouts that'll all fire about a second after you've exited the loop and logged "done".

To create a timer, you could conditionally call setTimeout within the callback:

new Promise((resolve, reject) => {
  let i = 0
  function increment () {
    i++
    console.log(i)
    if (i < 3) {
      setTimeout(increment, 1000)
    } else {
      console.log('done')
      resolve() // to mark the promise as completed
    }
  }
  setTimeout(increment, 1000)
})
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