单值的可观察与承诺

时间:2017-09-27 07:31:39

标签: javascript asynchronous promise rxjs observable

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

铊; DR:

|| (item.company ? && item.company.type !== null && item.company.type.toLowerCase().includes(searchByType) : true)

VS

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

1 个答案:

答案 0 :(得分:0)

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

即使您只需要返回一个值,我个人觉得使用Observable更容易。

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

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();
  }
}