What is the difference between Promises and Observables?

后端 未结 30 2694
小鲜肉
小鲜肉 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条回答
  •  旧时难觅i
    2020-11-22 00:20

    Promise vs Observable similarity first

    1. Both used to handle async code.
    2. Please look for promise example. Promise constructor passes a resolve reference function which will get called when it gets called with some value upon completion of some async task.

    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve("Hello from a Promise!");
      }, 2000);
    });
    
    promise.then(value => console.log(value));
    

    1. Observable example now. Here also we pass a function to observable, an observer to handle the async task. Unlike resolve in the promise it has the following method and subscribes in place of then.

    2. So both handles async tasks. Now let's see the difference.


    const observable = new Observable(observer => {
      setTimeout(() => {
        observer.next('Hello from a Observable!');
      }, 2000);
    });
    
    observable.subscribe(value => console.log(value));
    

    Promise vs Observable difference

    Promise

    1. It resolves or reject a single value and can handle a single value async task at a time.
    2. A promise once resolved the async value it completes, can no longer be used.its just one-time use and here it falls short.
    3. Not cancellable
    4. No rxjs support for operators.

    Observable

    1. ability to emit multiple asynchronous values.
    2. Used to handle the stream of events or values. Consider you have an array of numerous tasks or values, and you want every time value is inserted into this it should be handled automatically. Anytime you push a value into this array, all of its subscribers will receive the latest value automatically.
    3. Observables are useful for observing input changes, repeated interval, broadcast values to all child components, web socket push notifications etc.
    4. Can be cancelled using unsubscribe method anytime.
    5. One more last good part that promise that has is support for rxjs operators. You have many pipe operators majorly map, filter, switchMap, combineLatest etc. to transform observable data before subscribing.


提交回复
热议问题