What is the difference between Promises and Observables?

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

    Both Promises and Observables will help us work with the asynchronous functionalities in JavaScript. They are very similar in many cases, however, there are still some differences between the two as well, promises are values that will resolve in asynchronous ways like http calls. On the other hand, observables deal with a sequence of asynchronous events. The main differences between them are listed below:

    promise:

    • having one pipeline
    • usually only use with async data return
    • not easy to cancel

    observable:

    • are cancellable
    • are re-triable by nature such as retry and retryWhen
    • stream data in multiple pipelines
    • having array-like operations like map, filter etc
    • can be created from other sources like events
    • they are functions, which could be subscribed later on

    Also, I've created the graphical image for you below to show the differences visually:

提交回复
热议问题