What is the difference between Promises and Observables?

后端 未结 30 2613
小鲜肉
小鲜肉 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:41

    Short answer :

    Observable is better, it has all Promises features plus extra features.


    Long answer:

    Promises:

    • One Time Use "Return data once"
    • No cancel
    • One listener
    • No Socket Support One Listener

    Observable:

    • Return Data many times as data change
    • Support cancel
    • Support socket
    • Support many Listener and notify them when data change
    • Support map, filter, reduce
    0 讨论(0)
  • 2020-11-22 00:42

    Overview:

    • Both Promises and Observables help us dealing with asynchronous operations. They can call certain callbacks when these asynchronous operations are done.
    • A Promise can only handle one event, Observables are for streams of events over time
    • Promises can't be cancelled once they are pending
    • Data Observables emit can be transformed using operators

    You can always use an observable for dealing with asynchronous behaviour since an observable has the all functionality which a promise offers (+ extra). However, sometimes this extra functionality that Observables offer is not needed. Then it would be extra overhead to import a library for it to use them.

    When to use Promises:

    Use promises when you have a single async operation of which you want to process the result. For example:

    var promise = new Promise((resolve, reject) => {
      // do something once, possibly async
      // code inside the Promise constructor callback is getting executed synchronously
    
      if (/* everything turned out fine */) {
        resolve("Stuff worked!");
      }
      else {
        reject(Error("It broke"));
      }
    });
    
    //after the promise is resolved or rejected we can call .then or .catch method on it
    
    promise.then((val) => console.log(val))      // logs the resolve argument
           .catch((val) => console.log(val));    // logs the reject argument
    

    So a promise executes some code where it either resolves or rejects. If either resolve or reject is called the promise goes from a pending state to either a resolved or rejected state. When the promise state is resolved the then() method is called. When the promise state is rejected, the catch() method is called.

    When to use Observables:

    Use Observables when there is a stream (of data) over time which you need to be handled. A stream is a sequence of data elements which are being made available over time. Examples of streams are:

    1. User events, e.g. click, or keyup events. The user generates events (data) over time.
    2. Websockets, after the client makes a WebSocket connection to the server it pushes data over time.

    In the Observable itself is specified when the next event happened, when an error occurs, or when the Observable is completed. Then we can subscribe to this observable, which activates it and in this subscription, we can pass in 3 callbacks (don't always have to pass in all). One callback to be executed for success, one callback for error, and one callback for completion. For example:

    const observable = Rx.Observable.create(observer => {
      // create a single value and complete
      observer.onNext(1);
      observer.onCompleted();
    });
    
    source.subscribe(
      x => console.log('onNext: %s', x),   //  success callback
      e => console.log('onError: %s', e),  //  error callback
      () => console.log('onCompleted')     //  completion callback
     );
    
    // first we log: onNext: 1
    //  then we log: onCompleted
    

    When creating an observable it requires a callback function which supplies an observer as an argument. On this observer, you then can call onNext, onCompleted, onError. Then when the Observable is subscribed to it will call the corresponding callbacks passed into the subscription.

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

    Both Promises and Observables will help us work with the asynchronous functionalities in JavaScript. They are very similar in many cases, however, there are still some differences between the two as well, promises are values that will resolve in asynchronous ways like http calls. On the other hand, observables deal with a sequence of asynchronous events. The main differences between them are listed below:

    promise:

    • having one pipeline
    • usually only use with async data return
    • not easy to cancel

    observable:

    • are cancellable
    • are re-triable by nature such as retry and retryWhen
    • stream data in multiple pipelines
    • having array-like operations like map, filter etc
    • can be created from other sources like events
    • they are functions, which could be subscribed later on

    Also, I've created the graphical image for you below to show the differences visually:

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

    I see a lot of people using the argument that Observable are "cancellable" but it is rather trivial to make Promise "cancellable"

    function cancellablePromise(body) {
      let resolve, reject;
      const promise = new Promise((res, rej) => {
        resolve = res; reject = rej;
        body(resolve, reject)
      })
      promise.resolve = resolve;
      promise.reject = reject;
      return promise
    }
    
    // Example 1: Reject a promise prematurely
    const p1 = cancellablePromise((resolve, reject) => {
      setTimeout(() => resolve('10', 100))
    })
    
    p1.then(value => alert(value)).catch(err => console.error(err))
    p1.reject(new Error('denied')) // expect an error in the console
    
    // Example: Resolve a promise prematurely
    const p2 = cancellablePromise((resolve, reject) => {
      setTimeout(() => resolve('blop'), 100)
    })
    
    p2.then(value => alert(value)).catch(err => console.error(err))
    p2.resolve(200) // expect an alert with 200

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

    Promise

    A Promise handles a single event when an async operation completes or fails.

    Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.

    Observable

    An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event.

    Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.

    Observable also has the advantage over Promise to be cancellable. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the Subscription of an Observable allows to cancel the subscription, while a Promise will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore.

    While a Promise starts immediately, an Observable only starts if you subscribe to it. This is why Observables are called lazy.

    Observable provides operators like map, forEach, reduce, ... similar to an array

    There are also powerful operators like retry(), or replay(), ... that are often quite handy. A list of operators shipped with rxjs

    Lazy execution allows to build up a chain of operators before the observable is executed by subscribing, to do a more declarative kind of programming.

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

    Both Promises and Observables help us dealing with asynchronous operations. They can call certain callbacks when these asynchronous operations are done.

    Angular uses Observables which is from RxJS instead of promises for dealing with HTTP

    Below are some important differences in promises & Observables.

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