Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!