将 Observable 转换为 Promise [英] Converting Observable to Promise

查看:237
本文介绍了将 Observable 转换为 Promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将 observable 对象转换为 Promise 是否是一个好习惯,因为 observable 几乎可以用于所有场合而不是 promise?

Is it a good practice to convert the observable object to a promise since observable can be used in almost all the occasions instead of promise?

我最近开始学习 angular,并在我工作场所的一个新项目 (Angular 5) 中遇到了以下代码片段.此代码片段用于加载数据列表,例如客户列表.此客户列表数据集是作为一次性操作接收的,而不是作为流接收的.因此使用promise没有技术限制.但我想知道是否有任何缺点或限制.

I've started to learn angular recently and come across the below code snippet in a new project(Angular 5) at my workplace. This code snippet is used to load a list of data such as a customer list. This customer list data set is received as a one time action, not as a stream. Therefore it has no technical limitation to use promise. But I would like to know whether there are any drawbacks or limitations.

  getViewDataForPage(): Promise<any> {
    return this.commonDataService.getViewDataForPage(args_set)
      .toPromise()
      .catch(error => this._exceptionService.catchBadResponse(error));
  }


  //in commonDataService.ts
  getViewDataForPage(args_set): Observable<any> {
    /** logic goes here */
    return this.httpConnection.post(viewDataRequest, args);
  }

推荐答案

两者都可以使用.Observable 用于当您在一段时间内接收不同的值时更像是当您是某杂志的订阅者,而杂志 有新版本,您将成为通知者,所有订阅者都会发生同样的情况,每个人都会收到新的价值,或者在这种情况下是新杂志.

You can use both. The Observable is used when you are going to receive different values during the time is more like when you are a subscriptor in a some magazine, when ever the mazagazine has new edition you will be notifier and the same happens to all subscriptors and everybody receives the new value or in this case the new magazine.

Promise 的情况下,它就像一个可观察的 Async,但它只是发生的.

In the case of the Promise it is Async like an observable but it just happen ones.

那么如果下面的代码会发生在这种情况下是可以的承诺

Then if the following code will happens ones in this case is ok the promise

getViewDataForPage(): Promise<any> {
    return this.commonDataService.getViewDataForPage(args_set)
      .toPromise()
      .catch(error => this._exceptionService.catchBadResponse(error));
  }


  //in commonDataService.ts
  getViewDataForPage(args_set): Observable<any> {
    /** logic goes here */
    return this.httpConnection.post(viewDataRequest, args);
  }

这篇关于将 Observable 转换为 Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆