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

204
Visualizações
How to reset or override a running async loop

I have an async function foo with an inner async iterate that has a loop. The loop awaits an inner promise to resolve before continuing. The outer async awaits iterate to finish before proceeding. I want to implement a reset button which restarts the loop.

Rerunning iterate in the handler, a new parallel running instance of the loop is made which can be run to completion. The issue is that foo is still waiting the first instance to complete. Is there a way to do this properly?

async function foo() {
  async function iterate() {
    for (let i = 0; i < 5; i++) {
       const position = await new Promise() // Resolves after the user does something
       // do stuff
    }
  }

  button.onclick = async () => await iterate(); // Set up event handler

  await iterate(); // First call

  // Button gets clicked -> Second call takes over 
  // Now first call never ends and can't finish `foo()`

} 
about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

I was finally able to do it by using promises and more specifically, calling resolve() after the loop, and more importantly, in the handler:

async function foo() {

  async function iterate() {
    await new Promise(async (resolve) => {

      button.onclick = async () => {
        await iterate(); // Set up event handler
        resolve();
      }

      for (let i = 0; i < 5; i++) {
        const position = await new Promise()
        // do stuff
      }
      resolve();
  }

  await iterate();
}

That way, even if initial loop never ends, when the call in the handler finishes, the handler itself calls resolve() and we exit this fooking mess.

This is only mildly hacky, but if someone has a more concise or direct approach, I'd be happy to check it out.

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