Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda