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?

2
  • 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 Commented Apr 21, 2022 at 3:29
  • await only works with promises, and setTimeout does not create a promise. To promisify setTimeout, see this question stackoverflow.com/a/22707551/3794812 . And then make sure to await that promise, or return it Commented Apr 21, 2022 at 3:29

1 Answer 1

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 
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.