What is the difference between Promises and Observables?

后端 未结 30 2657
小鲜肉
小鲜肉 2020-11-21 23:48

What is the difference between Promise and Observable in Angular?

An example on each would be helpful in understanding both the cases. In w

相关标签:
30条回答
  • 2020-11-22 00:36

    In a nutshell, the main differences between a Promise and an Observable are as follows:

    • a Promise is eager, whereas an Observable is lazy,
    • a Promise is always asynchronous, while an Observable can be either synchronous or asynchronous,
    • a Promise can provide a single value, whereas an Observable is a stream of values (from 0 to multiple values),
    • you can apply RxJS operators to an Observable to get a new tailored stream.

    a more detailed can be found in this article

    0 讨论(0)
  • 2020-11-22 00:39

    Promise - Provide a single future value. Not lazy . Not cancel-able. It will either reject or resolve.

    Observable - Provide multiple future value. Lazy . Cancel-able . It provide other methods live map,filter,reduce.

    0 讨论(0)
  • 2020-11-22 00:39

    Below are some important differences in promises & Observables.

    Promise

    • Emits a single value only
    • Not cancellable
    • Not sharable
    • Always asynchronous

    Observable

    • Emits multiple values
    • Executes only when it is called or someone is subscribing
    • Can be cancellable
    • Can be shared and subscribed that shared value by multiple subscribers. And all the subscribers will execute at a single point of time.
    • possibly asynchronous

    For better understanding refer to the https://stackblitz.com/edit/observable-vs-promises

    0 讨论(0)
  • 2020-11-22 00:39
    1. a Promise is eager, whereas an Observable is lazy,
    2. a Promise is always asynchronous, while an Observable can be either synchronous or asynchronous,
    3. a Promise can provide a single value, whereas an Observable is a
      stream of values (from 0 to multiple values),
    4. you can apply RxJS operators to an Observable to get a new tailored stream.
    0 讨论(0)
  • 2020-11-22 00:40

    I've just dealt with an issue where Promises were the best solution, and I'm sharing it here for anyone stumbling across this question in the event it's useful (this was exactly the answer I was looking for earlier):

    In an Angular2 project I have a service that takes some parameters and returns a value list to populate drop down menus on a form. When the form component initializes, I need to call the same service multiple times with different parameters to define a number of different dropdown menus, however if I simply queue up all the variables to call the service, only the last one succeeds and the rest error out. The service fetching from the database could only handle one request at a time.

    The only way to successfully populate all the dropdown menu variables was to call the service in a way that prevented a new request from being processed until the last request was finished, and the Promise / .then mechanism solved the problem nicely.

      fetchValueList(listCode): Promise<any> {
          return this.dataSvc.getValueList(listCode, this.stateSvc.currentContext, this.stateSvc.currentLanguageCode)
              .map(response => response.json())
              .toPromise();
      }
    
      initializeDropDowns() {
          this.fetchValueList('First-Val-List')
              .then(data => {
                  this.firstValList = data;
                  return this.fetchValueList('Second-Val-List')
              }).then(data => {
                  this.secondValList = data;
                  return this.fetchValueList('Third-Val-List')
              }).then(data => {
                  this.thirdValList = data;
              })  }
    

    I defined the functions in the component, and then called initializeDropDowns() in ngOnInit.

    The fetchValueList function returns a Promise, so the first call passes the first listCode and when the Promise resolves, the return value is in the data variable in the .then block where we can assign it to the this.firstValList variable. As the function has returned data, we know the service has finished and it's safe to call again with the second listCode, the return value is in the data variable in the next .then block and we assign it to the this.secondValList variable.

    We can chain this as many times as required to populate all the variables, and on the last code block we simply omit the return statement and the block terminates.

    This is a very specific use case where we have a single service that needs to be called multiple times as the component initializes, and where the service has to complete its fetch and return a value before it can be called again, but in this case, the Promise / .then method was ideal.

    0 讨论(0)
  • 2020-11-22 00:41

    I believe all the other answers should clear your doubts. Nevertheless, I just wanted to add that observables are based on functional programming, and I find very useful the functions that come with it like map, flatmap, reduce, zip. The consistency the web achieves especially when it depends on API requests is a brutal improvement.

    I strongly recommend this documentation, since it's the official documentation of reactiveX and I find it to be the most clear out there.

    If you want to get into observables, I would suggest this 3-part post: http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/

    Although it's meant for RxJava, the concepts are the same, and it's really well explained. In reactiveX documentation, you have the equivalences for each function. You must look for RxJS.

    0 讨论(0)
提交回复
热议问题