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 !!!
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();
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.
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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With