Home > OS >  Async Waiting for Function 1 to Finish before running function 2
Async Waiting for Function 1 to Finish before running function 2

Time:08-16

What is the Correct Async Usage here to get FetchJoke() to finish before letting openDialog() Run

async getrandomJoke(query: string){
      
      this.fetchJoke(query);
      
      this.openDialog();
    }

Update:

The issue is : randomJoke: any; Is undefined by the time it gets to openDialog() even with the await keyword

See below:

async getrandomJoke(query: string)
 {
      await this.fetchJoke(query);

      console.log(this.randomJoke   "var"); //Undefined.
    
      this.openDialog();
 }
  fetchJoke(query: string){
       this.apiService.randomJoke(query).subscribe(
        (data => 
          { 
             this.randomJoke = data;
             console.log(this.randomJoke   "varinside");//[Object object]
          }))
    }

No Values are getting sent through to Dialog(). As It seems to run before Fetchjoke()Is finished

CodePudding user response:

You need to make your fetchJoke return a promise :

 fetchJoke(query: string){
       return firstValueFrom(this.apiService.randomJoke(query))
 }

Then await it !

async getrandomJoke(query: string){
  const joke =  await this.fetchJoke(query); // will wait for fetchJoke to finish to continue 
  this.openDialog(joke);
}

CodePudding user response:

You should use await in this case:

async getrandomJoke(query: string){
      await this.fetchJoke(query);      
      this.openDialog();
}
  • Related