What is the difference between observables and promises on Angular 5?
What
Is Promise?
Promise handles a single event when an asynchronous
(async) operation completes or fails.
It helps us to run functions asynchronously and return
only one value (or exception) when executed.
Promise is not Lazy.
What
Is Observable?
Observable is like a Stream and allows us to pass zero or more events where the callback
is called for each events.
Observable provides operators like map, forEach, reduce
and similar to an array.
Observable is preferred over Promise because it
provides the features of Promise and more.
Promise
-
1. Returns
a single value
2. Not
cancellable - It can be Reject or Resolve
3. More
readable code with try/catch and async/await
4. Promise
is not Lazy.
Observable
-
1. Works
with multiple values over time
2. Cancellable
3. By
default, it is Lazy as it emits values when time progresses.
4. It
is cancel-able/retry-able and supports operators such as map, filter, reduce
etc.
5. Use
Reactive Extensions (RxJS)
6. An
array whose items arrive asynchronously over time
Both Promises and Observables will help us work
with the asynchronous functionalities in JavaScript applications.