What is the difference between Promises and Observables?

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

    A Promise emits a single event when an async activity finishes or fails.

    An Observable is like a Stream (in many languages) and permits to pass at least zero or more events where the callback is required for every event.

    Frequently Observable is preferred over Promise since it gives the highlights of Promise and more. With Observable it doesn't matter if you need to handle 0, 1, or various events. You can use the similar API for each case.

    Promise: promise emits a single value

    For example:

    const numberPromise = new Promise((resolve) => {
        resolve(5);
        resolve(10);
    });
    
    numberPromise.then(value => console.log(value));
    // still prints only 5
    

    Observable: Emits multiple values over a period of time

    For example:

      const numberObservable = new Observable((observer) => {
            observer.next(5);
            observer.next(10);
        });
    
    numberObservable.subscribe(value => console.log(value));
    // prints 5 and 10
    

    we can think of an observable like a stream which emits multiple values over a period of time and the same callback function is called for each item emitted so with an observable we can use the same API to handled asynchronous data. whether that data is transmitted as a single value or multiple values over some stretch of time.

    Promise:

    • A promise is Not Lazy
    • A Promise cannot be cancelled

    Observable:

    • Observable is Lazy. The "Observable" is slow. It isn't called until we are subscribed to it.
    • An Observable can be cancelled by using the unsubscribe() method
    • An addition Observable provides many powerful operators like map, foreach, filter, reduce, retry, retryWhen etc.

    Angular Promises vs Observables

提交回复
热议问题