1

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?

Benevos
  • 135
  • 10
  • 2
    there's no Promise in firstFunction, and nothing to await, so why is it async? async isn't magic, it's just for awaiting promises – Bravo Apr 21 '22 at 03:29
  • `await` only works with promises, and setTimeout does not create a promise. To promisify setTimeout, see this question https://stackoverflow.com/a/22707551/3794812 . And then make sure to await that promise, or return it – Nicholas Tower Apr 21 '22 at 03:29

1 Answers1

2

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 
}
Bravo
  • 6,022
  • 1
  • 10
  • 15