What is the difference between Promises and Observables?

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

    Promises

    1. Definition: Helps you run functions asynchronously, and use their return values (or exceptions) but only once when executed.
    2. Not Lazy
    3. Not cancellable( There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far). The two possible decisions are
      • Reject
      • Resolve
    4. Cannot be retried(Promises should have access to the original function that returned the promise to have a retry capability, which is a bad practice)

    Observables

    1. Definition: Helps you run functions asynchronously, and use their return values in a continuous sequence(multiple times) when executed.
    2. By default, it is Lazy as it emits values when time progresses.
    3. Has a lot of operators which simplifies the coding effort.
    4. One operator retry can be used to retry whenever needed, also if we need to retry the observable based on some conditions retryWhen can be used.

      Note: A list of operators along with their interactive diagrams is available here at RxMarbles.com

提交回复
热议问题