Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 4 : How to use await/async within subscribe

Tags:

I can honestly say await/async in angular is really a great stuff, it reduces a lot of braces, improves readability and prevent a lot of human error. However, one thing puzzles me a lot. how can I use await/async inside subscribe.

let's say

 @Injectable()
export class TableCom extends BaseCom {
  public subject = new Subject<any>();

}

TableCom is a provider serves as a communicator between a signalr component and a page component.

so inside the page component constructor, it is using the observable subject to receive new data from signalr component as shown below.

constructor(protected nav: NavController,
        protected db: Storage,
        protected alert: AlertController,
        protected order: OrderData,
        protected translate: TranslateService,
        public navParams: NavParams,
        public toastCtrl: ToastController,
        private table_data: TableData,
        private load: LoadingController,
        private http: Http,
        private com_table: TableCom

    )
    {
        super(nav, db, alert, order, translate, undefined, false);
        this.previous_page = navParams.get('previous_page');
        this.subscribe_table = this.com_table.Receive().subscribe(res =>
        {
            await this.SaveTableAsync(res.data);
            this.ReadTableAsync();
        });
    }

the issue is that the this.ReadTableAsync() basically has to wait this.SaveTableAsync to be finished before starting. await can be achieved here ? thank you in advance !!

like image 657
Steven Li Avatar asked Jul 20 '17 19:07

Steven Li


People also ask

Can we use async await in subscribe?

As you may know, subscriptions are used to handle async method call. Thus, the code inside the subscribe() method is executed only when the async method return its result (after a http call for instance). While waiting for the async response, the program continues and execute the following code.

Can you await a subscribe?

You cannot await Observables directly, however you can await a Promise .

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.

Can I use async await with Observable?

You can use Observables with Promises and with async/await to benefit from the strengths of each of those tools.


1 Answers

You need the async keyword to mark the function as "async":

this.subscribe_table = this.com_table.Receive().subscribe(async res => {
    await this.SaveTableAsync(res.data);
    this.ReadTableAsync();
});
like image 133
ideaboxer Avatar answered Sep 20 '22 13:09

ideaboxer