首页 文章

单值的可观察与承诺

提问于
浏览
4

Typescript(现在也是ECMAScript 2017)为您提供了非常好的异步工具,可以以async / await的形式使用 . 但是,使用Angular 4,我觉得使用Observables是首选 . 我的问题是:当我有一个函数返回 single value once (例如:确认模式)时,使用observables有什么大的优点,还是承诺(async / await)首选/同样好?使用observables不奇怪吗?它们不代表 Value 观吗?

TL;博士:

async showDialog(msg: string): Promise<DialogResult>

showDialog(msg: string): Observable<DialogResult>

1 回答

  • 0

    你使用哪一个并不重要 . Promise和Observables可以自由互换 . 看看这个https://medium.com/@benlesh/rxjs-observable-interop-with-promises-and-async-await-bebb05306875

    我个人觉得使用Observables更容易,即使你只需要返回一个值 .

    使用Promises,您经常需要保留三个属性:

    class Whatever {
      resolve: Function;
      reject: Function;
      promise = new Promise((resolve, reject) => {
        this.resolve = resolve;
        this.reject = reject;
      });    
    
      method() {
        return this.promise;
      }
    
      otherMethod() {
        this.resolve();
      }
    }
    

    使用Observables,您只能保留Subject的实例:

    class Whatever {
      subject = new Subject();
    
      method() {
        return this.subject.toPromise();
      }
    
      otherMethod() {
        this.subject.next(...);
        this.subject.complete();
      }
    }
    

相关问题