Wednesday, August 7, 2019

Angular CLI - How to use async and await

In Angular Cli, we can use async and await to perform service calls to wait for the promise. Usually we do call first service and then in subscribe method we do perform other logics. But now we can use toPromise method with asyn/await to perform the same as below,

Existing approach:


saveMethod(){
this.someService.getFirstResult().subscribe((data) ={
//second service depend on first service data
this.someService.getSecondResult(data.id).subscribe((data2) => {
        //Do perform your business logics here..
});
});
}


Aysnc/Await approach:

async saveMethod(){
let data = await this.someService.getFirstResult().toPromise();
//second service depend on first service data
let data2 = await this.someService.getSecondResult(data.id).toPromise();
//Do perform your business logics here..
}


No comments:

Post a Comment