OnceUponATime
OnceUponATime

Reputation: 35

Async Waiting for Function 1 to Finish before running function 2

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

Upvotes: 0

Views: 42

Answers (2)

Matthieu Riegler
Matthieu Riegler

Reputation: 55744

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);
}

Upvotes: 2

Drashti Kheni
Drashti Kheni

Reputation: 1140

You should use await in this case:

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

Upvotes: 0

Related Questions