What is the difference between Promises and Observables?

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

提交回复
热议问题