Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for function with subscribe to finish in angular 8?

I want to wait for one function to finish before executing the function next to it. I have one function called getData() in which http call occurs which returns an observable. The second function checkDuplicate() we have subscribed to that function getData() . and we have third function called proceed() in which we call the checkDuplicate() function and once the checkDuplicate() function is completed, we are calling alert("finished"). But the issue here is even before checkDuplicate() function is completed, alert has been triggered.

find the code for better clarification:

getData(): Observable<any>{
  return this.http.get<any>(URL...);
}

checkDuplicate(){

return this.getData().subscribe(response => {
   if(response){
      console.log("Inside");
  }
});
}

proceed(){
 this.checkDuplicate();
 console.log("finished");
}

Actual Result

finished

Inside

Expected result

Inside

finished

I have tried asyn/await to wait for checkDuplicate() function to finish. But still no use. It would be grateful if u share the solution. Thanks in Advance !!!

like image 465
sherin shaf Avatar asked Jul 28 '20 14:07

sherin shaf


People also ask

How do you wait for a function to finish in typescript?

Wait for function to finish using async/await keywords As you already know from the Promise explanation above, you need to chain the call to the function that returns a Promise using then/catch functions. The await keyword allows you to wait until the Promise object is resolved or rejected: await first(); second();

Does subscribe wait for response Angular?

Basically the console. log(this. newIds) is runned first and is always empty because the subscribe doesn't wait for response to come from the backend.

Can we use async await in Angular?

Using Async/Await in Angular Basically, Async/Await works on top of Promise and allows you to write async code in a synchronous manner. It simplifies the code and makes the flow and logic more understandable.


Video Answer


1 Answers

The gotcha of async programming. Here's a solution with promises (you can also use observables):

getData(): Observable<any>{
  return this.http.get<any>(URL...);
}

async checkDuplicate(){
  var response = await this.getData().toPromise();
  if (response) {
      console.log("Inside");
  }
}

async proceed(){
 await this.checkDuplicate();
 console.log("finished");
}
like image 110
Andrei Tătar Avatar answered Sep 19 '22 14:09

Andrei Tătar