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()`
}
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.