Is there any case, where Promise is more powerful as compare to observable? I know a lot of benefits of observables over promises. But Is there any case, I should use only promises over observables.
I found this link, promises vs observables. But this always shows me the benefits of observables over promises. I want to know the benefits of promise over observables.
Often Observable is preferred over Promise because it provides the features of Promise and more. With Observable it doesn't matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case. Observable also has the advantage over Promise to be cancellable.
The biggest difference is that Promises won't change their value once they have been fulfilled. They can only emit (reject, resolve) a single value. On the other hand, observables can emit multiple results. The subscriber will be receiving results until the observer is completed or unsubscribed from.
Promises reject/resolve a single event. An Observable will emit events where a defined callback executes for each event. If you want to handle a single event, use a Promise. If you want to stream multiple events from the same API, use Observables.
Promises are used in Angular to resolve asynchronous operations, and Observables are used when the data comes from an external source like an API. Promises can be resolved with a single value or an array of values, and Observables emit one or more values over time.
An observable does everything that a promise does and more. It can always be switched to a promise with toPromise()
method in case a promise is expected.
An observable must be chosen over a promise if
Observable.from(...)
safety structure to unify observables and promisesAn observable may be chosen over a promise if the code where it's used uses observables exclusively.
A promise must be chosen over an observable if API that consumes it expects a promise and doesn't use Observable.from(...)
safety structure.
A promise may be chosen over an observable if
async
functions)let observable = ...; observable.subscribe(...); return observable
(this also requires multiple subscriptions to be tracked in case an observable is cancellable)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With