What is the difference between Promises and Observables?

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

    Even though this answer is late, i have summarized the differences below,

    Observable:

    1. Observable is just a function that takes an observer and returns a function Observer: an object with next, error.
    2. Observer allows to subscribe/unsubscribe to its data stream, emit next value to the observer, notify the observer about errors and inform the observer about the stream completion
    3. Observer provides a function to handle next value,errors and end of stream(ui events,http responses,data with web sockets).
    4. Works with multiple values over time
    5. It is cancel-able/retry-able and supports operators such as map,filter,reduce etc.
    6. Creating an Observable can be -Observable.create() - returns Observable that can invoke methods on -Observer Observable.from() - converts an array or iterable into -Observable Observable.fromEvent() - converts an event into Observable -Observable.fromPromise() - converts a Promise into Observable -Observable.range() - returns a sequence of integers in the specified range

    Promise:

    1. A promise represents a task that will finish in the future;

    2. Promises become resolved by a value;

    3. Promises get rejected by exceptions;

    4. Not cancellable and it returns a single value

    5. A promise expose a function (then)

      -then returns a new promise;

      -allows for the attachment of that will be executed based on state;

      -handlers are guaranteed to execute in order attached;

提交回复
热议问题