Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

What is the difference between Promises and Observables?

Get support on Angular & Typescript related technology.
Post Reply
admin
Site Admin
Posts: 45

What is the difference between Promises and Observables?

Post by admin » Mon Oct 14, 2019 3:53 pm

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:

Promises
Definition: Helps you run functions asynchronously, and use their return values (or exceptions) but only once when executed.
Not Lazy
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
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)
having one pipeline
usually only use with async data return
not easy to cancel

Observables
Definition: Helps you run functions asynchronously, and use their return values in a continuous sequence(multiple times) when executed.
By default, it is Lazy as it emits values when time progresses.
Has a lot of operators which simplifies the coding effort.
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.
  • [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:
Image

Post Reply