25

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.

4
  • Possible duplicate of Promise vs Observable
    – ForestG
    Commented May 10, 2018 at 10:07
  • this answer is always showing the observables benefits over promises. but I want to know the benefits of promises. Commented May 10, 2018 at 10:11
  • 1
    Promises are a native part of the language. Promises are interoperable. Promises are simple. Promises can be subscribed at any time. Promises can only resolve once.
    – Bergi
    Commented May 10, 2018 at 10:30
  • 2
    I don't think it's a duplicate or 'too broad' question. I believe that the main criterion of 'too broad' is that it needs to be clarified to receive a quality answer, or there is infinite amount of possible quality answers. This one is specific enough to receive it. Commented May 10, 2018 at 12:04

6 Answers 6

26

An observable does everything that a promise does and more. It can always be switched to a promise in case one is expected with toPromise() method (firstValueFrom and lastValueFrom in RxJS 7).

An observable must be chosen over a promise if

  • any features that are intrinsic to observables and not promises and explained in detail in related question is in demand (notably unsubscription, incomplete observables and observables that receive multiple values)
  • API that consumes it expects an observable and doesn't use Observable.from(...) safety structure to unify observables and promises

An 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

  • the code where it's used uses promises exclusively (notably async functions)
  • it needs to be asynchronous by design
  • it needs to be immediately subscribed and chained then, because a chain should be broken in observables let observable = ...; observable.subscribe(...); return observable (this also requires multiple subscriptions to be tracked in case an observable is cancellable)
3
  • 2
    small update to this: toPromise() is deprecated now. But you can use lastValueFrom or firstValueFrom indepth.dev/posts/1287/…
    – ForestG
    Commented May 2, 2022 at 13:54
  • That's true. But actually, what is your feeling about the syntax using firstValueFrom instead of toPromise()? Isn't it odd? I was more than happy to use toPromise(). Now, using firstValueFrom I feel like writing some hacks in the code.
    – Krystian
    Commented Apr 1, 2023 at 20:52
  • @Krystian Not a good naming but proper move, toPromise is neat but stands out from other observable implementations and isn't really that special for it to not be extracted to an operator. There may be more than one way in which it could be used, there's also defaultValue option in lastValueFrom and firstValueFrom Commented Apr 2, 2023 at 17:33
17

Use Promise instead of an Observable, when:

  • You need to handle the (future response) event no matter what (no unsubscribe, no cancel: after you subscribe, there will be an answer, 100%, and you will have to handle it, 100%, the code will get executed)
  • One Subscription = One Event handling: there will be only one event from the source, so the future response and the completition is the same event.

Use Observable instead of a Promise, when:

  • You want to have the ability to accept multiple events from the same source
  • You need a "I am finished with this event stream" handler
  • You want to be able to unsubscribe from a possibly never ending stream of data, and re-subscribe anytime (meaning also that you might don't really need to fulfill the subscription at all: for instance, if nothing happens in 10 sec, let's unsubscribe, nobody will ever handle the late answer)
  • You want to use the RxJS "Stream API" to preprocess the data of your responses.

Generally, the Observable pattern is an extended Promise pattern, with a lot more tools and functionality. It is up to you to decide to limit the code with Promises or not. It was first a custom libary, then got included in ES2016.

Also, I suggest researching the issue with specific problem parameters: you need the app to be faster? You will use legacy modules?

4

Observable is lazy --> nothing will happen until we subscribed the observable. Observable can be cancelled at anytime by unsubscribing it for memory clean up. Promise can have only one response but observable can have more than one responses.

const promSingle = new Promise(resolve){
  resolve('a');
  resolve('b');
}
promSingle.then(value => {
  console.log(value)
})

Print only a In Observable :

const obSerMult = new Observable(observable){
  Observable.next('a');
  Observable.next('b');
  Observable.next('c');
  Observable.next('d');
}

obSerMult.subscribe(value => {
  console.log(value);
})
print will be a, b , c ,d
3

Promises are eager, hence use them where you want something to happen immediately without any trigger. whereas Observable are lazy, which can be used to do something that requires some triggers either from input or something else and does not need to be happen immediately the app is loads

2

From: Randall Koutnik book “Build Reactive Websites with RxJS.” :

Observables are like arrays in that they represent a collection of events, but are also like promises in that they’re asynchronous: each event in the collection arrives at some indeterminate point in the future. This is distinct from a collection of promises (like Promise.all) in that an observable can handle an arbitrary number of events, and a promise can only track one thing. An observable can be used to model clicks of a button. It represents all the clicks that will happen over the lifetime of the application, but the clicks will happen at some point in the future that we can’t predict.

From: Anton Moiseev Book “Angular Development with Typescript, Second Edition.” :

Promise has the following shortcomings:

There’s no way to cancel a pending request made with a promise.

When a promise resolves or rejects, the client receives either data or an error message, but in both cases it’ll be a single piece of data. A JavaScript promise doesn’t offer a way to handle a continuous stream of data chunks delivered over time.

Observables don’t have these shortcomings.

2

Have a look at this article: https://scholarbasta.com/promises-vs-observables/

Promises are used when,

  1. You really do not need to unsubscribe to this event.
  2. The event completes in one go.
  3. The event doesn't really consume much of your memory.

Use observables when:

  1. You need to unsubscribe to this event,
  2. Multiple streams are being emitted and you need to perform various operations on them. Say you need to filter/ map some values. The Rxjs library is pretty powerful in that way.
  3. There are multiple values from the same source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.