'How to make a function wait until its recursive instances are completed too? - Javascript [duplicate]

I have two functions in JS, one calls another, but the first one tries again itself after one second if a condition goes false. The problem is, I want the second function to await until this recursive instances are done too.

Here's what I have until now:

async function firstFunction(){
  if(SomeCondition){
    //do something
  }
  else{
    //do something
    setTimeout(() => {
      firstFunction();
    }, 1000);
    //Tries again in 1 second
  }
}

async function secondFunction(){
  await firstFunction() //waiting firstFunction and its instances to finish 
}

Can't figure out how to solve this, any idea?



Solution 1:[1]

Since you've made firstFunction async - use Promises to do what you need

async function firstFunction() {
  if (SomeCondition) {
    //do something
  } else {
    //do something
    await new Promise(r => setTimeout(r, 1000))
    await firstFunction();
  }
}

async function secondFunction() {
  await firstFunction() //waiting firstFunction and its instances to finish 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bravo