Angular 4:如何在subscribe中使用await / async

时间:2021-06-10 19:03:25

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.

我可以诚实地说,角度等待/异步真的是一个很棒的东西,它减少了很多大括号,提高了可读性并防止了很多人为错误。然而,有一件事困扰了我很多。如何在subscribe中使用await / async。

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.

TableCom是一个提供者,用作信号器组件和页面组件之间的通信器。

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

所以在页面组件构造函数中,它使用可观察主题从signalr组件接收新数据,如下所示。

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

问题是this.ReadTableAsync()基本上必须等待this.SaveTableAsync才能在开始之前完成。等待可以在这里实现吗?先谢谢你 !!

1 个解决方案

#1


10  

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

您需要使用async关键字将该函数标记为“async”:

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

#1


10  

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

您需要使用async关键字将该函数标记为“async”:

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