Angular 4 : How to use await/async within subscrib

2020-02-08 06:00发布

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 !!

2条回答
狗以群分
2楼-- · 2020-02-08 06:41

Where is the implementation of SaveTableAsync() because this method needs to return a promise to be awaited.

Since the subscribe() method takes an arrow function, you can simply add the async keyword before the definition i.e:

subscribe(async res => {
    await this.SaveTableAsync(res.data);
    this.ReadTableAsync();
});

If you the ReadTableAsync() method returns an Observable, you first need to use the toPromise() method to return a promise from the observable before you can asynchronously await for it

查看更多
做自己的国王
3楼-- · 2020-02-08 06:50

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();
});
查看更多
登录 后发表回答