Reputation: 153
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 !!!
Upvotes: 9
Views: 41429
Reputation: 21
Lost a lot of time on this one. You have to use lastValueFrom
as specified here: Conversion to Promises. ToPromise()
has been deprecated.
import { lastValueFrom, tap } from 'rxjs';
getData(): Observable<any>{
return this.http.get<any>(URL...);
}
async checkDuplicate(){
return await lastValueFrom(this.getData()
.pipe(tap(response => {
if(response){
console.log("Inside");
}
})
));
}
async proceed(){
await this.checkDuplicate();
console.log("finished");
}
Upvotes: 1
Reputation: 149
You can update something like this.
getData(): Observable<any>{
return this.http.get<any>(URL...);
}
checkDuplicate() {
return Promise(resolve=>{
this.getData().subscribe(response => {
if(response){
console.log("Inside");
}
resolve(true);
});
});
}
proceed(){
this.checkDuplicate().then(value=>{
console.log("Return from promise => "+ value);
console.log("finished");
});
}
You can return promise from checkDuplicate and call another function after it is resolved by using "then".
Upvotes: 0
Reputation: 8295
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");
}
Upvotes: 8