1582

What is the difference between Promise and Observable in Angular?

An example on each would be helpful in understanding both the cases. In what scenario can we use each case?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Rohit
  • 15,907
  • 3
  • 8
  • 9
  • 26
    I would suggest you to read this post; [Angular2 promise vs observable](http://chariotsolutions.com/blog/post/angular2-observables-http-separating-services-components/) – erolkaya84 May 21 '16 at 16:00
  • 7
    in simpler terms https://angular-2-training-book.rangle.io/handout/observables/observables_vs_promises.html – Pardeep Jain Jun 13 '17 at 12:16
  • 5
    To anyone reading this Q&A - as someone who is involved in both worlds from a maintainer, speaker and long time user PoV I encourage you to read the official RxJS docs and the MDN documentation on promises. **I personally find the answers here entirely misleading and incorrect** and believe they are, while with good intentions from people trying to help, very harmful. – Benjamin Gruenbaum Oct 03 '18 at 11:39
  • 4
    I would suggest you to read this angular official document https://angular.io/guide/comparing-observables – fgul Mar 24 '19 at 06:29
  • 1
    a Promise is always asynchronous, while an Observable can be either synchronous or asynchronous, a Promise can provide a single value, whereas an Observable is a stream of values (from 0 to multiple values), you can apply RxJS operators to an Observable to get a new tailored stream – achraf akrouti Sep 16 '20 at 14:07
  • A must watch [https://youtu.be/uQ1zhJHclvs](https://youtu.be/uQ1zhJHclvs) – HirenParekh Nov 06 '20 at 07:35
  • The link: https://mydaytodo.com/rxjs-observables-vs-javascript-promise/ top mu p does a good job of explaining the difference between the two and what scenarios to best apply both at, – cptdanko Feb 25 '21 at 12:14

30 Answers30

1757

Promise

A Promise handles a single event when an async operation completes or fails.

Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.

Observable

An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event.

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. If the result of an HTTP request to a server or some other expensive async operation isn't needed anymore, the Subscription of an Observable allows to cancel the subscription, while a Promise will eventually call the success or failed callback even when you don't need the notification or the result it provides anymore.

While a Promise starts immediately, an Observable only starts if you subscribe to it. This is why Observables are called lazy.

Observable provides operators like map, forEach, reduce, ... similar to an array

There are also powerful operators like retry(), or replay(), ... that are often quite handy. A list of operators shipped with rxjs

Lazy execution allows to build up a chain of operators before the observable is executed by subscribing, to do a more declarative kind of programming.

Günter Zöchbauer
  • 490,478
  • 163
  • 1,733
  • 1,404
  • 205
    So is there a good reason to use Promise instead of Observable in the single callback case or should Observables also be used there since they can work that way too? Basically, is it good practice to "Observable all the things" or does Promise still have its place? – Josh Werts Jul 21 '16 at 14:42
  • 87
    If you want to use the reactive style, just use observables everywhere. If you have observables only you can easy compose. If you mix them it's not so clean anymore. If you don't care about reactive style, you can use promise for single events where you don't care about cancelable and observable for streams of events. – Günter Zöchbauer Jul 21 '16 at 14:45
  • 2
    For a good intro resource on Observables/RxJs/Reactive Programming: https://gist.github.com/staltz/868e7e9bc2a7b8c1f754 ("The introduction to Reactive Programming you've been missing") – mrshickadance Jan 23 '17 at 19:37
  • 3
    @JoshWerts I was asking the same question about a week or two ago. Did a lot of research. As far as I am concerned there is just NOT a good reason to use Observables over Promises for http. None of the advantages are really relevant here in practice. With that said, now that I understand Observables, I am too lazy to write "toPromise()" – VSO Jan 30 '17 at 16:03
  • 1
    @VSO what are the arguments against `Observable`, or why do you think the arguments for `Observable` are not valid or not strong enough? – Günter Zöchbauer Jan 30 '17 at 16:05
  • 43
    @GünterZöchbauer Hey - I have no arguments against Observables or functional programming. I am simply stating that I believe that people running into Observables mainly via http in NG2 have no real reason whatsoever to use Observables over Promises to make the calls. They lose nothing practical by using promises. The debounce and retry operators are irrelevant - you can debounce with ng-debounce and if a call is expected to fail, generally, there is a problem with the code. The only time I needed to work with retrying calls was while querying unstable third-party APIs for HVT. – VSO Jan 30 '17 at 16:08
  • 1
    And just to stress this again - I completely agree with your explanation and you helped me a ton while I was starting out. I am just saying there is no significant value-added in THIS particular use case - your answer (and several others by you on the topic) are all great. – VSO Jan 30 '17 at 16:10
  • @VSO I agree that in the normal use cases there is not much difference. For more advanced scenarios it can make IMHO quite a difference. Also the `Http` API might change a bit over time and make better use of `Observables` . `Http` is still quite basic. – Günter Zöchbauer Jan 30 '17 at 16:11
  • @VSO I also wouldn't say that using `toPromise` is a bad idea. Only if you are using `Observables` everywhere in a reative-like programming style, this really can show its potential. Thanks a lot for your feedback. I didn't perceive it as criticism. I'm just curious what you learned and perhaps can share something new to me. – Günter Zöchbauer Jan 30 '17 at 16:12
  • 1
    @GünterZöchbauer Maybe you are right - this is just my opinion from working with Observable http calls in NG2 and tons of experience with standard promises in NG1. I also ended up taking 2 classes on RxJS since we last talked, so I feel like I have a good grip on what Observables provide. – VSO Jan 30 '17 at 16:13
  • 6
    @VSO I agree - I can see the advantages of Observable over Promise, but there are often times where there's a single callback and that's it. In this case, I think Observable creates code that is a little harder to understand, so I just toPromise() in this case. Mixing does hurt consistency a little. Basically, no right/wrong answer IMO. – Josh Werts Jan 30 '17 at 18:25
  • 1
    Re: promises not able to be cancelled. Is this just in angular 2? In angularJS, promises can be cancelled with a timeout parameter. – dz210 Apr 19 '17 at 14:30
  • 2
    They can be made to complete with an error prematurely, but that doesn't cancel the operation. – Günter Zöchbauer Apr 19 '17 at 14:33
  • 2
    Can anybody tell me, how the ability to cancel an `Observable` is an advantage over `Promises`? When using promises, I can chain them and control whether the next promise in the chain should be fired or not. – Ronin May 01 '17 at 17:41
  • 1
    A `Promise` (ES6) can't be cancelled while waiting for an async call to complete, while Observable does. This cancellation might propagate back to the producer of the async result and might even stop an expensive calculation, while a `Promise` would still do the expensive calculation even when the receiver already decided to not not be interested in the result anymore and won't wait for it. – Günter Zöchbauer May 01 '17 at 22:25
  • 3
    In scenarios where my api call returns a single thing (ie a JSON object or array of objects) I have found myself using a "hot" observable. `vendors: Observable = this.http.get(url).map(res => res.json()).publishLast().refCount();` The cool thing about using Observable in this case is you can subscribe to it in multiple places and it won't requery. Anyway, just one reason to use Observables. – yanbu Jun 01 '17 at 22:27
  • 126
    But please don't forget that `Promise`, along with `async`/`await` makes your code flat again! In a majority of situations, and in projects that don't deal with rocket science, there is no need to write those horrible nested functions with unnecessarily complicated chains of methods. You can use `async`/`await` today with transpilers, like `TypeScript`, and write actual human-readable flat code without any of the `rxjs` boilerplate. You will probably still need `rxjs` sometimes in select situations, because it really does have a lot of things to offer. – evilkos Jul 02 '17 at 13:59
  • 21
    This answer is misleading, an observable is _not_ like a stream it is like a _function that returns a stream_. – Benjamin Gruenbaum Jul 03 '17 at 14:59
  • 4
    @evilkos in my experience, nesting when using rxjs happens only when doing it wrong. If done right you rarely need more than one level of indentation as the pipeline is a pretty powerful concept. Nesting mainly happens when you subscribe to everything instead of chaining observables. – Ingo Bürk Feb 04 '18 at 10:16
  • @GünterZöchbauer if only single value is returned `Promise` or `Observable` any one can be used. When stream of values being returned that's where `Observable` shine and also with some addition features it has with `retry()`, `forEach`, calcelable etc. I am bit newbie to this, so can you please provide an example where an api would return stream of values? Also any example where api request need to be canceled? – Vivek Apr 26 '18 at 07:57
  • @Vivek "where api request need to be canceled" if you make an expensive request to a server and the user navigates away from the current route, you might want to cancel that request. "stream of values" a simple example would be a service that provides the `isLoggedIn` state. A component or service might want to get notified about changes. The component or service subscribes to an Observable and gets notified whenever the user logs in or out. Another example would be a progress bar component that gets passed an Observable the provides progress updates. – Günter Zöchbauer Apr 26 '18 at 08:06
  • 1
    @GünterZöchbauer "if you make an expensive request to a server and the user navigates away from the current route, you might want to cancel that request" how this request can be cancelled? – Vivek Apr 30 '18 at 04:30
  • 1
    @Vivek store the subscription and unsubscribe to cancel https://stackoverflow.com/questions/42664741/easiest-way-to-unsubscribe-subscriptions-angular/42664776#42664776 – Günter Zöchbauer Apr 30 '18 at 05:30
  • 2
    @Vivek Or you can use takeUntil which I find cleaner and easier to use, but it depends on what framework you are using. In Angular you would use it in combination with ngOnDestroy for example. – Enn May 18 '18 at 19:25
  • 1
    cancelling a Promise is the wrong way to think about promises. The Promise's responsibility it only to record success or failure in an async compatible way. If you want to cancel an http request you cancel the request, not the promise, and make the result of cancelling either fulfill or reject the Promise. https://jsfiddle.net/greggman/ea0yhd4p/ – gman Dec 10 '18 at 14:46
  • 1
    @BenjaminGruenbaum I couldn't agree more. This is one of the most confusing parts of using Observables and I think it _really_ should be addressed here. The fact that subscribing to an Observable can have side effects (but doesn't always) is the main reason I don't like using them. – Yona Appletree Dec 19 '18 at 22:07
  • 1
    Copied content from - https://hype.codes/differences-between-promise-and-observable-angular – Pardeep Jain Jan 18 '19 at 12:43
  • 3
    @PardeepJain thanks for pointing it out. I haven't found a way to leave a comment. I just enjoy that this answer has become so popular that some find it worth stealing :D – Günter Zöchbauer Jan 18 '19 at 13:37
  • @GünterZöchbauer can you elaborate a bit about "a stream"? I mean, do you expect that the server just pushed stuff to the client? Doesn't 99% of the web applications request a single thing from the server and then process it? – Roger Far Apr 04 '19 at 14:08
  • 1
    Observable and Promise have nothing to do with client and server, they are only about async results (that may or may not come from a response to a server request. Promise is for a single async result while Observable is about a series of results (zero or more) that arrive over time. Like for example from the DOM `onLoad` (Promise - exactly once) or `mouseMove` (Observable - series of results until you unsubscribe) – Günter Zöchbauer Apr 04 '19 at 14:15
  • Once you've understood both, usage boils down to the requirement. Such as, what if you only want to make 1 http request and reuse the response across multiple places and at different times - this is because, as mentioned before, an observable is a "stream". – Miguel Felipe Guillen Calo Apr 29 '19 at 03:47
  • Really interesting read. Wouldn't a good design pattern be to build all `Http` requests as `Observables` within the service and upon usage in components, you could either use it as the standard `Observable` or use it as a `Promise` by utilizing `.toPromise()` – Rossco May 03 '19 at 07:36
  • 1
    I think this is exactly why Angular uses Observable for (one-shot) HTTP requests. You can of course follow this pattern in your own code as well. This allows easy combining with all rxjs operators. – Günter Zöchbauer May 03 '19 at 07:53
  • @JoshWerts, I asked myself the same question and found the following article explaining it nicely. (https://netbasal.com/angular-stop-using-observable-when-you-should-use-a-promise-8da0788a8d2). – Niels Ferguson Dec 05 '19 at 10:04
  • 2
    I started using Promise a few years ago and have got used to its pattern, but then it defaults to Observable in Angular. it seems to make no difference to me as I have no need for the new features for the Observable. It is very handy though you can covert any return to Promise with the toPomise() function. – Steve Mar 01 '20 at 23:53
  • I think Promise has definitely place for using in http requests because it uses javascript natural asynchronous engine (libuv, event-loop, microtasks queue), while Observable is executing in the main Execution stack thus are not truly asynchronous. As for other stuff, I do not see much use of cancelation possibility. And about executing a stream of events, it is better done with dedicated tools like socket.io. I use both libs but humbly think Observables are overrated. Whenever I can I stay with Promises which are very powerful, especially if you use promise.all() – Dan Nov 03 '20 at 15:22
371

Both Promises and Observables provide us with abstractions that help us deal with the asynchronous nature of our applications. The difference between them was pointed out clearly by @Günter and @Relu.

Since a code snippet is worth a thousand words, let go through the below example to understand them easier.

Thanks @Christoph Burgdorf for the awesome article


Angular uses Rx.js Observables instead of promises for dealing with HTTP.

Suppose that you are building a search function that should instantly show you results as you type. Sound familiar but there are a lot of challenges that come with that task.

  • We don't want to hit the server endpoint every time user presses a key, it should flood them with a storm of HTTP requests. Basically, we only want to hit it once the user has stopped typing instead of with every keystroke.
  • Don’t hit the search endpoint with the same query params for subsequent requests.
  • Deal with out-of-order responses. When we have multiple requests in-flight at the same time we must account for cases where they come back in unexpected order. Imagine we first type computer, stop, a request goes out, we type car, stop, a request goes out. Now we have two requests in-flight. Unfortunately, the request that carries the results for computer comes back after the request that carries the results for car.

The demo will simply consist of two files: app.ts and wikipedia-service.ts. In a real world scenario, we would most likely split things further up, though.


Below is Promise-based implementation that doesn’t handle any of the described edge cases.

wikipedia-service.ts

import { Injectable } from '@angular/core';
import { URLSearchParams, Jsonp } from '@angular/http';

@Injectable()
export class WikipediaService {
  constructor(private jsonp: Jsonp) {}

  search (term: string) {
    var search = new URLSearchParams()
    search.set('action', 'opensearch');
    search.set('search', term);
    search.set('format', 'json');
    return this.jsonp
                .get('http://en.wikipedia.org/w/api.php?callback=JSONP_CALLBACK', { search })
                .toPromise()
                .then((response) => response.json()[1]);
  }
}

We are injecting the Jsonp service to make a GET request against the Wikipedia API with a given search term. Notice that we call toPromise in order to get from an Observable<Response> to a Promise<Response>. Eventually end up with a Promise<Array<string>> as the return type of our search method.

app.ts

// check the plnkr for the full list of imports
import {...} from '...';

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Wikipedia Search</h2>
      <input #term type="text" (keyup)="search(term.value)">
      <ul>
        <li *ngFor="let item of items">{{item}}</li>
      </ul>
    </div>
  `
})
export class AppComponent {
  items: Array<string>;

  constructor(private wikipediaService: WikipediaService) {}

  search(term) {
    this.wikipediaService.search(term)
                         .then(items => this.items = items);
  }
}

Not much of a surprise here either. We inject our WikipediaService and expose it’s functionality via a search method to the template. The template simply binds to keyup and calls search(term.value).

We unwrap the result of the Promise that the search method of the WikipediaService returns and expose it as a simple Array of strings to the template so that we can have *ngFor loop through it and build up a list for us.

See the example of Promise-based implementation on Plunker


Where Observables really shine

Let’s change our code to not hammer the endpoint with every keystroke but instead only send a request when the user stopped typing for 400 ms

To unveil such super powers we first need to get an Observable<string> that carries the search term that the user types in. Instead of manually binding to the keyup event, we can take advantage of Angular’s formControl directive. To use this directive, we first need to import the ReactiveFormsModule into our application module.

app.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { JsonpModule } from '@angular/http';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [BrowserModule, JsonpModule, ReactiveFormsModule]
  declarations: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Once imported, we can use formControl from within our template and set it to the name "term".

<input type="text" [formControl]="term"/>

In our component, we create an instance of FormControl from @angular/form and expose it as a field under the name term on our component.

Behind the scenes, term automatically exposes an Observable<string> as property valueChanges that we can subscribe to. Now that we have an Observable<string>, overcoming the user input is as easy as calling debounceTime(400) on our Observable. This will return a new Observable<string> that will only emit a new value when there haven’t been coming new values for 400ms.

export class App {
  items: Array<string>;
  term = new FormControl();
  constructor(private wikipediaService: WikipediaService) {
    this.term.valueChanges
              .debounceTime(400)        // wait for 400ms pause in events
              .distinctUntilChanged()   // ignore if next search term is same as previous
              .subscribe(term => this.wikipediaService.search(term).then(items => this.items = items));
  }
}

It would be a waste of resources to send out another request for a search term that our app already shows the results for. All we have to do to achieve the desired behavior is to call the distinctUntilChanged operator right after we called debounceTime(400)

See the example of Observable implementation on Plunker

For dealing with out-of-order responses, please check the full article http://blog.thoughtram.io/angular/2016/01/06/taking-advantage-of-observables-in-angular2.html

As far as I am using Http in Angular, I agree that in the normal use cases there is not much difference when using Observable over Promise. None of the advantages are really relevant here in practice. Hope I can see some advanced use case in the future :)


Learn more

Luca Ritossa
  • 607
  • 5
  • 18
trungk18
  • 18,147
  • 6
  • 41
  • 69
  • 40
    I don't completely buy the decision of turning Http service into Observable based. Every explanation I hear relies on the same example: The search by term. But that one is about handling browser events. I would like to hear what the advantage is in applying it when dealing with asynchronous http requests. – Alex Pollan Feb 02 '17 at 07:37
  • 1
    Was the decision accidental to avoid mixed patterns? – Alex Pollan Feb 02 '17 at 07:43
  • 6
    @AlexPollan, there's actually a good explanation for benefits of the http service returning an observable on this podcast with Ben Lesh: https://devchat.tv/js-jabber/jsj-248-reactive-programming-and-rxjs-with-ben-lesh. Ultimately, the major benefit is that you can cancel an observable, and a use case for this described in the link above - while a little contrived - is that if you call out to multiple apis and only care about the first response, no matter which of the apis you called gets back to you first, you can then cancel the requests to the others. – nikolasleblanc Mar 16 '17 at 14:09
  • 2
    @nikolasleblanc, Im pretty sure you can use $q.race() for that? – jameslouiz Mar 29 '17 at 09:28
  • 1
    Both of your Plunker projects are broken. Looks like it couldn't find some resources. 'Failed to load resources: the server returned with a status of 404 ()' https://npmcdn.com/@angular/platform-browser@2.0.0-rc.5//bundles/platform-browser.umd.js – CatGuardian Aug 23 '18 at 17:46
  • doesn't `valueChanges` trigger only when value is changed? so whats the usage of `.distinctUntilChanged()` ? – yaya Aug 14 '19 at 16:53
  • 2
    Consider you type foo, stop, type another o, followed by an immediate backspace and rest back at foo. That should be just one request with the term foo and not two even if we technically stopped twice after we had foo in the search box. That's what distinctUntilChanged did. You can check more example from https://www.learnrxjs.io/operators/filtering/distinctuntilchanged.html – trungk18 Aug 15 '19 at 02:23
  • 4
    @AlexPollan, The advantage is that an Observable-based HTTP service makes it easy to cancel mid-flight HTTP requests. The race condition in trungk18's answer can be solved by simply unsubscribing from the HTTP observable prior to making a subsequent request. RXJS switchMap can be used for HTTP requests triggered by another observable (e.g. valueChanges). For standalone HTTP observables, you can unsubscribe and re-subscribe manually. – Stevethemacguy Jan 16 '20 at 02:44
  • All that can be easily done by using Promises and a little knowledge of how js work under the hood. As for cancelling feature, it is like Yeti, everybody talks about it but nobody has seen real use of it. – Dan Nov 03 '20 at 15:35
275

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:

Promises and Observables image

Alireza
  • 83,698
  • 19
  • 241
  • 152
  • 4
    promise "not easy to cancel" , is it possible to cancel them ? – Pardeep Jain Jun 13 '17 at 12:18
  • 14
    yes, there is a way to cancel them as well... some people use bluebird or third party libraries... also using Q library in Angular there are ways to cancel it... but as I said not very handy – Alireza Jun 13 '17 at 12:28
  • Having one pipeline sometimes has advantange, ex. in APP_INITIALIZER, if you have multiple pipeline it can never finish sometimes or finish multiple times. – windmaomao May 18 '18 at 13:37
  • running across this issue APP_INITILIZER code I inherited uses observable it is not very clear or usable, I just need to fetch some configuration from a web service it's a one off fail or success event clearly tailored for Promises. Is there an easy way to make it behave like a Promisse... what I mean is the 'then' behavior, since the results cascade heavily on the return of each other. – Astronaut Jun 26 '18 at 17:23
  • 11
    cancelling a `Promise` is the wrong way to think about how promises. The `Promise`'s responsibility it only to handle success or failure in an async compatible way.. If you want to cancel an http request you cancel the request, not the promise, and make the result of cancelling either fulfil or reject the Promise. https://jsfiddle.net/greggman/ea0yhd4p/ – gman Nov 30 '18 at 04:42
  • 5
    @gman Exactly. The Promise simply represents some future _value_. It does _not_ represent the _operation which generates the value_. You cannot cancel a value. You cannot retry a value. It's just a value. It may or may not be _present_ yet, and it may _never_ exist because an exception occurred, but that's it. – Yona Appletree Dec 19 '18 at 22:10
  • @gman has explained Promise basis quite well. I think people wrongly suppose that Promises should do something that they are not intended for, Actually, they are very good at doing what they are supposed to do. – Dan Nov 03 '20 at 15:48
86

There is one downside of Observables missing in the answers. Promises allow to use the ES7 async/await functions. With them you can write asynchronous code like it would be a synchronous function call, so you don't need callbacks anymore. The only possibility for Observables to do this, is to convert them to Promises. But when you convert them to Promises, you can only have one return value again:

async function getData(){
    const data = await observable.first().toPromise();
    //do stuff with 'data' (no callback function needed)
}

Further reading: How can I `await` on an Rx Observable?

besserwisser
  • 1,780
  • 1
  • 11
  • 16
  • 26
    Also surprised why no one pointed out this killer perk of Promises - simplicity and transparency thanks to async/await. I switched to Promises just for the ability of writing flat code. Simple business logic and UI interaction code shouldn't look like rocket science and be polluted by the nested hell of reactive extensions. Also, async/await is not only in the future, you can use it in public production apps now using transpilers. I use TypeScript 2.3 and it's awesome, like a real language. – evilkos Jul 02 '17 at 13:38
  • 1
    Nice, but thinking in a reactive way and all with the RxOperators maybe this is not a killer feature – JorgeTovar Jun 11 '19 at 17:35
  • 1
    I use Promise async/await all the time and it is really powerful. It provides code familiarity and clarity while using a true async javascript engine. In contrast, Observables are synchronous, they are executed in the main Execution stack while Promise async/await use js asynchronous features in engine: event loop, libuv, microtasks queue etc. Making Observables asynchronous by using setTimeout() is silly because it is a resource hog and you cannot control the order of execution in the event-loop. It uses the WebAPI part of the event loop, while the events in the microtask queue have priority – Dan Nov 03 '20 at 16:05
  • This answer should definitely get more votes. Observables are powerful, and with great power comes great complexity and callback-hell/callback-pyramid-of-doom type of code. Use Observables in places where you need some of their advanced features. Stick to async/await with Promises for simple cases, and your code will be 10x easier to understand. – huancz Nov 10 '20 at 02:07
83

Promises

  1. Definition: Helps you run functions asynchronously, and use their return values (or exceptions) but only once when executed.
  2. Not Lazy
  3. 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
  4. 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)

Observables

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

    Note: A list of operators along with their interactive diagrams is available here at RxMarbles.com

Naveen DA
  • 3,007
  • 3
  • 32
  • 42
Aravind
  • 36,165
  • 14
  • 84
  • 102
45

Promises and Observables both handle the asynchronous call only.

Here are the differences between them:

Observable

  1. Emits multiple values over a period of time
  2. Is not called until we subscribe to the Observable
  3. Can be canceled by using the unsubscribe() method
  4. Provides the map, forEach, filter, reduce, retry, and retryWhen operators

Promise

  1. Emits only a single value at a time

  2. Calls the services without .then and .catch

  3. Cannot be canceled

  4. Does not provide any operators

jkdev
  • 9,037
  • 14
  • 52
  • 75
sudheer nunna
  • 1,192
  • 12
  • 16
  • 2
    What exactly do you mean by promise emits only single value, while observable emits multiple – Abel Apr 08 '18 at 16:32
  • 2
    A promise does not emit a value at all - a promise _is_ a value over time. A promise multicasts that value to multiple subscribers - once you hold the promise you already have a value. An observable is like a _function_, subscribing to it invokes the action. – Benjamin Gruenbaum Jun 17 '18 at 16:02
  • 1
    @BenjaminGruenbaum Still I didn't get the mean of multiple subscribers can you please provide a link or example. Thanks – Deepak Patidar Jul 03 '18 at 06:17
  • 2
    observable1.subscribe(subscriber1), observable1.subscribe(subscriber2) - this invokes the _function_ multiple times. – Benjamin Gruenbaum Jul 03 '18 at 12:26
  • 2
    Please **[edit]** your post and show the actual text instead of screenshots. Others can't copy and paste from your images, and also can't help you fix the many grammar errors. [See here](https://meta.stackoverflow.com/a/285557/1402846) for details. Thank you. – Pang Dec 14 '18 at 04:49
  • 1
    @sudheernunna please update the image. Did you copy paste from kudvenkat videos? And grammar is also not proper in the text in image. – Pratik May 19 '19 at 18:03
  • 1
    Yes Pratik, I have changed Image file to text, feel free to change If any grammatical mistakes Thankyou :) – sudheer nunna May 20 '19 at 04:52
30

Even though this answer is late, i have summarized the differences below,

Observable:

  1. Observable is just a function that takes an observer and returns a function Observer: an object with next, error.
  2. Observer allows to subscribe/unsubscribe to its data stream, emit next value to the observer, notify the observer about errors and inform the observer about the stream completion
  3. Observer provides a function to handle next value,errors and end of stream(ui events,http responses,data with web sockets).
  4. Works with multiple values over time
  5. It is cancel-able/retry-able and supports operators such as map,filter,reduce etc.
  6. Creating an Observable can be -Observable.create() - returns Observable that can invoke methods on -Observer Observable.from() - converts an array or iterable into -Observable Observable.fromEvent() - converts an event into Observable -Observable.fromPromise() - converts a Promise into Observable -Observable.range() - returns a sequence of integers in the specified range

Promise:

  1. A promise represents a task that will finish in the future;

  2. Promises become resolved by a value;

  3. Promises get rejected by exceptions;

  4. Not cancellable and it returns a single value

  5. A promise expose a function (then)

    -then returns a new promise;

    -allows for the attachment of that will be executed based on state;

    -handlers are guaranteed to execute in order attached;

Sajeetharan
  • 186,121
  • 54
  • 283
  • 331
25

I've just dealt with an issue where Promises were the best solution, and I'm sharing it here for anyone stumbling across this question in the event it's useful (this was exactly the answer I was looking for earlier):

In an Angular2 project I have a service that takes some parameters and returns a value list to populate drop down menus on a form. When the form component initializes, I need to call the same service multiple times with different parameters to define a number of different dropdown menus, however if I simply queue up all the variables to call the service, only the last one succeeds and the rest error out. The service fetching from the database could only handle one request at a time.

The only way to successfully populate all the dropdown menu variables was to call the service in a way that prevented a new request from being processed until the last request was finished, and the Promise / .then mechanism solved the problem nicely.

  fetchValueList(listCode): Promise<any> {
      return this.dataSvc.getValueList(listCode, this.stateSvc.currentContext, this.stateSvc.currentLanguageCode)
          .map(response => response.json())
          .toPromise();
  }

  initializeDropDowns() {
      this.fetchValueList('First-Val-List')
          .then(data => {
              this.firstValList = data;
              return this.fetchValueList('Second-Val-List')
          }).then(data => {
              this.secondValList = data;
              return this.fetchValueList('Third-Val-List')
          }).then(data => {
              this.thirdValList = data;
          })  }

I defined the functions in the component, and then called initializeDropDowns() in ngOnInit.

The fetchValueList function returns a Promise, so the first call passes the first listCode and when the Promise resolves, the return value is in the data variable in the .then block where we can assign it to the this.firstValList variable. As the function has returned data, we know the service has finished and it's safe to call again with the second listCode, the return value is in the data variable in the next .then block and we assign it to the this.secondValList variable.

We can chain this as many times as required to populate all the variables, and on the last code block we simply omit the return statement and the block terminates.

This is a very specific use case where we have a single service that needs to be called multiple times as the component initializes, and where the service has to complete its fetch and return a value before it can be called again, but in this case, the Promise / .then method was ideal.

Luca Ritossa
  • 607
  • 5
  • 18
Stephen R. Smith
  • 3,040
  • 1
  • 22
  • 37
  • 3
    This is certainly also possible with (higher-order) observables. You could for instance use `scan()` to build a stream of sequential observables. However, your approach is maybe more explicit and easier to understand. – lex82 Apr 27 '17 at 11:51
  • 2
    You could replace "then" with "switchMap" and do the exact same thing w/observables. – Dr. C. Hilarius Aug 28 '17 at 17:33
  • 1
    The problem with switchMap, as I understand it, is that it will start all the requests in parallel and wait until they all return, then return the values to the calling function whereas in my situation, I have a single server that I can't call multiple times in parallel (as the server will drop unfinished requests when new ones come in), so I had to make sure each call to the database service completed before starting a new call, and the Promise/then seemed to be the best and perhaps only way to solve that. – Stephen R. Smith Aug 28 '17 at 18:32
  • 1
    Why didn't you use chained mergeMap? As far as I understood your code, this one is pretty simple and does the job as good as your example. @StephenR.Smith – Ore Dec 18 '17 at 14:03
  • 1
    @Ore Can you add a code example of that solving the same problem as another answer? Would be a good reference and may be a good refactoring opportunity in the future. The requirement is that whatever code can't call the backend service in parallel, it has to call, wait for the return value and call again. – Stephen R. Smith Dec 19 '17 at 15:37
  • 1
    May I point out how much easier to read this would be with `async`/`await`? `async initializeDropDowns() { this.firstValList = await this.fetchValueList('First-Val-List'); this.secondValList = await this.fetchValueList('Second-Val-List'); this.thirdValList = await this.fetchValueList('Third-Val-List'); }` – Yona Appletree Dec 19 '18 at 22:03
  • Using `async`/`await` here is a great example of Promises being cleaner and easier to read that Observables. Though I would really look into why that backend service cannot handle multiple concurrent calls. What about when a user has two tabs open to your page? Or if you have two users... – Yona Appletree Dec 19 '18 at 22:06
  • @YonaAppletree Each tab gets its own session, so multiple users don't have an issue, but multiple calls to the same service with different parameters at the same time causes issues. I have no control over the server side, so I'm having to deal with the limitations of the services as provided. Your async/await example is similarly clean to the chained promise approach, I think either works just as well. – Stephen R. Smith Dec 21 '18 at 19:58
25

I believe all the other answers should clear your doubts. Nevertheless, I just wanted to add that observables are based on functional programming, and I find very useful the functions that come with it like map, flatmap, reduce, zip. The consistency the web achieves especially when it depends on API requests is a brutal improvement.

I strongly recommend this documentation, since it's the official documentation of reactiveX and I find it to be the most clear out there.

If you want to get into observables, I would suggest this 3-part post: http://blog.danlew.net/2014/09/15/grokking-rxjava-part-1/

Although it's meant for RxJava, the concepts are the same, and it's really well explained. In reactiveX documentation, you have the equivalences for each function. You must look for RxJS.

Pang
  • 8,605
  • 144
  • 77
  • 113
Marc Pérez
  • 274
  • 3
  • 8
23

Overview:

  • Both Promises and Observables help us dealing with asynchronous operations. They can call certain callbacks when these asynchronous operations are done.
  • A Promise can only handle one event, Observables are for streams of events over time
  • Promises can't be cancelled once they are pending
  • Data Observables emit can be transformed using operators

You can always use an observable for dealing with asynchronous behaviour since an observable has the all functionality which a promise offers (+ extra). However, sometimes this extra functionality that Observables offer is not needed. Then it would be extra overhead to import a library for it to use them.

When to use Promises:

Use promises when you have a single async operation of which you want to process the result. For example:

var promise = new Promise((resolve, reject) => {
  // do something once, possibly async
  // code inside the Promise constructor callback is getting executed synchronously

  if (/* everything turned out fine */) {
    resolve("Stuff worked!");
  }
  else {
    reject(Error("It broke"));
  }
});

//after the promise is resolved or rejected we can call .then or .catch method on it

promise.then((val) => console.log(val))      // logs the resolve argument
       .catch((val) => console.log(val));    // logs the reject argument

So a promise executes some code where it either resolves or rejects. If either resolve or reject is called the promise goes from a pending state to either a resolved or rejected state. When the promise state is resolved the then() method is called. When the promise state is rejected, the catch() method is called.

When to use Observables:

Use Observables when there is a stream (of data) over time which you need to be handled. A stream is a sequence of data elements which are being made available over time. Examples of streams are:

  1. User events, e.g. click, or keyup events. The user generates events (data) over time.
  2. Websockets, after the client makes a WebSocket connection to the server it pushes data over time.

In the Observable itself is specified when the next event happened, when an error occurs, or when the Observable is completed. Then we can subscribe to this observable, which activates it and in this subscription, we can pass in 3 callbacks (don't always have to pass in all). One callback to be executed for success, one callback for error, and one callback for completion. For example:

const observable = Rx.Observable.create(observer => {
  // create a single value and complete
  observer.onNext(1);
  observer.onCompleted();
});

source.subscribe(
  x => console.log('onNext: %s', x),   //  success callback
  e => console.log('onError: %s', e),  //  error callback
  () => console.log('onCompleted')     //  completion callback
 );

// first we log: onNext: 1
//  then we log: onCompleted

When creating an observable it requires a callback function which supplies an observer as an argument. On this observer, you then can call onNext, onCompleted, onError. Then when the Observable is subscribed to it will call the corresponding callbacks passed into the subscription.

Naveen DA
  • 3,007
  • 3
  • 32
  • 42
Willem van der Veen
  • 19,609
  • 11
  • 116
  • 113
22

Promise:

  • Provide a single future value;
  • Not lazy;
  • Not cancellable;

Observable:

  • Emits multiple values over time;
  • Lazy;
  • Cancellable;
  • Supports map, filter, reduce and similar operators

You can use promises instead of observables when calling HTTP in Angular if you wish.

Community
  • 1
  • 1
Iosua Sipos
  • 411
  • 4
  • 9
13

Promise - Provide a single future value. Not lazy . Not cancel-able. It will either reject or resolve.

Observable - Provide multiple future value. Lazy . Cancel-able . It provide other methods live map,filter,reduce.

Gajender Singh
  • 963
  • 9
  • 12
12

Promise vs Observable similarity first

  1. Both used to handle async code.
  2. Please look for promise example. Promise constructor passes a resolve reference function which will get called when it gets called with some value upon completion of some async task.

const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve("Hello from a Promise!");
  }, 2000);
});

promise.then(value => console.log(value));

  1. Observable example now. Here also we pass a function to observable, an observer to handle the async task. Unlike resolve in the promise it has the following method and subscribes in place of then.

  2. So both handles async tasks. Now let's see the difference.


const observable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Hello from a Observable!');
  }, 2000);
});

observable.subscribe(value => console.log(value));

Promise vs Observable difference

Promise

  1. It resolves or reject a single value and can handle a single value async task at a time.
  2. A promise once resolved the async value it completes, can no longer be used.its just one-time use and here it falls short.
  3. Not cancellable
  4. No rxjs support for operators.

Observable

  1. ability to emit multiple asynchronous values.
  2. Used to handle the stream of events or values. Consider you have an array of numerous tasks or values, and you want every time value is inserted into this it should be handled automatically. Anytime you push a value into this array, all of its subscribers will receive the latest value automatically.
  3. Observables are useful for observing input changes, repeated interval, broadcast values to all child components, web socket push notifications etc.
  4. Can be cancelled using unsubscribe method anytime.
  5. One more last good part that promise that has is support for rxjs operators. You have many pipe operators majorly map, filter, switchMap, combineLatest etc. to transform observable data before subscribing.

enter image description here


ymynem
  • 13
  • 5
ramesh sharma
  • 164
  • 1
  • 7
12

Promise emits a single value while Observable emits multiple values. So, while handling a HTTP request, Promise can manage a single response for the same request, but what if there are multiple responses to the same request, then we have to use Observable. Yes, Observable can handle multiple responses for the same request.

Promise

const promise = new Promise((data) =>
{ data(1);
  data(2);
  data(3); })
.then(element => console.log(‘Promise ‘ + element));

Output

Promise 1

Observable

const observable = new Observable((data) => {
data.next(1);
data.next(2);
data.next(3);
}).subscribe(element => console.log('Observable ' + element));

Output

Observable 1
Observable 2
Observable 3
Yogesh Waghmare
  • 496
  • 3
  • 6
10

A Promise emits a single event when an async activity finishes or fails.

An Observable is like a Stream (in many languages) and permits to pass at least zero or more events where the callback is required for every event.

Frequently Observable is preferred over Promise since it gives the highlights of Promise and more. With Observable it doesn't matter if you need to handle 0, 1, or various events. You can use the similar API for each case.

Promise: promise emits a single value

For example:

const numberPromise = new Promise((resolve) => {
    resolve(5);
    resolve(10);
});

numberPromise.then(value => console.log(value));
// still prints only 5

Observable: Emits multiple values over a period of time

For example:

  const numberObservable = new Observable((observer) => {
        observer.next(5);
        observer.next(10);
    });

numberObservable.subscribe(value => console.log(value));
// prints 5 and 10

we can think of an observable like a stream which emits multiple values over a period of time and the same callback function is called for each item emitted so with an observable we can use the same API to handled asynchronous data. whether that data is transmitted as a single value or multiple values over some stretch of time.

Promise:

  • A promise is Not Lazy
  • A Promise cannot be cancelled

Observable:

  • Observable is Lazy. The "Observable" is slow. It isn't called until we are subscribed to it.
  • An Observable can be cancelled by using the unsubscribe() method
  • An addition Observable provides many powerful operators like map, foreach, filter, reduce, retry, retryWhen etc.

Angular Promises vs Observables

DeC
  • 1,706
  • 18
  • 32
8

Both Promises and Observables help us dealing with asynchronous operations. They can call certain callbacks when these asynchronous operations are done.

Angular uses Observables which is from RxJS instead of promises for dealing with HTTP

Below are some important differences in promises & Observables.

difference between Promises and Observables

Community
  • 1
  • 1
Srikrushna
  • 2,652
  • 30
  • 37
  • 1
    Please **[edit]** your post and show the actual content as text instead of screenshots. Others can't copy and paste from your images. [See here](https://meta.stackoverflow.com/a/285557/1402846) for details. Thank you. – Pang May 03 '19 at 01:33
5

Short answer :

Observable is better, it has all Promises features plus extra features.


Long answer:

Promises:

  • One Time Use "Return data once"
  • No cancel
  • One listener
  • No Socket Support One Listener

Observable:

  • Return Data many times as data change
  • Support cancel
  • Support socket
  • Support many Listener and notify them when data change
  • Support map, filter, reduce
Amr Ibrahim
  • 1,482
  • 2
  • 13
  • 40
  • I don't think you can say Observables are objectively better. There are number of downsides to Observables noted in the various answers here. The ones that stand out to me are Observable's complexity, and that they don't work directly with await/async. I personally find them really hard to work with because you cannot determine the behavior of an Observable when using it -- you have to look at the code that generated it. Whereas with a Promise, you know exactly how they work, always. For example, sometimes subscribing to an Observable has side effects (e.g. an http request), but sometimes not. – Yona Appletree Dec 19 '18 at 21:57
  • For angular, it depend on your case. for most cases we will work with services and some data which will affect different places, sockets, cancellation, map, filter and reduce. so it will be better on those cases as promises not supporting them. so again it depend on your case – Amr Ibrahim Dec 20 '18 at 17:37
5

Below are some important differences in promises & Observables.

Promise

  • Emits a single value only
  • Not cancellable
  • Not sharable
  • Always asynchronous

Observable

  • Emits multiple values
  • Executes only when it is called or someone is subscribing
  • Can be cancellable
  • Can be shared and subscribed that shared value by multiple subscribers. And all the subscribers will execute at a single point of time.
  • possibly asynchronous

For better understanding refer to the https://stackblitz.com/edit/observable-vs-promises

Bikram
  • 213
  • 2
  • 10
5

While the accepted answer is good in general I don't think it emphasises that when dealing with Angular Components you almost always want to use an Observable because it supports cancelation. Promises cannot be cancelled and will resolve even if your component is destroyed. Angular tends to be forgiving until it's not.

For example any manual change detection on a destroyed component will cause an exception:

ngOnInit() {
  // promise api
  this.service.getData().then(d => {
     this.data = d;
     this.changeDetectorRef.detectChanges();
  });

  // observable api
  this.service.getData().pipe(takeUntil(this.unsubscribe)).subscribe((d) => {
     this.data = d;
     this.changeDetectorRef.detectChanges();
  });
}

If your component is destroyed before the promise is resolved, you'll get an attempt to use destroyed view error when the promise is resolved.

Alternatively, if you use observables with the takeUntil pattern, then as soon as your component is destroyed the subscription will be cancelled.

This is a bit of a contrived example but executing code for a component that is destroyed is probably going to lead to bugs. Unless you actually want to do that for some reason :p

shusson
  • 4,746
  • 30
  • 34
5

Promise:

An Async Event Handler - The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.

Syntax: new Promise(executor);

Eg:

var promise_eg = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});

promise_eg.then(function(value) {
  console.log(value);
  // expected output: "foo"
});

console.log(promise_eg);

enter image description here

About Promise: It has one pipeline so, it will return values only once when its called. its one way handler so once called you may not able to cancel. useful syntax you can play around, when() and then()

Observables:

Observables are lazy collections of multiple values over time. its really a great approach for async operations. it can be done with rxjs which has cross platform support can use with angular/react etc.

its act like stream liner. can be multi pipeline. so once defined you can subscribe to get return results in many places.

Syntax: import * as Rx from "@reactivex/rxjs"; to init:

Rx.Observable.fromEvent(button, "click"),
Rx.Subject()

etc

to subscribe: RxLogger.getInstance();

Eg:

import { range } from 'rxjs';
import { map, filter } from 'rxjs/operators';

range(1, 200).pipe(
  filter(x => x % 2 === 1),
  map(x => x + x)
).subscribe(x => console.log(x));

since it support multi pipeline you can subscribe result in different location, enter image description here it has much possibilities than promises.

Usage: it has more possibilities like map, filter, pipe, map, concatMap etc

Mohideen bin Mohammed
  • 14,471
  • 7
  • 86
  • 95
5

In a nutshell, the main differences between a Promise and an Observable are as follows:

  • a Promise is eager, whereas an Observable is lazy,
  • a Promise is always asynchronous, while an Observable can be either synchronous or asynchronous,
  • a Promise can provide a single value, whereas an Observable is a stream of values (from 0 to multiple values),
  • you can apply RxJS operators to an Observable to get a new tailored stream.

a more detailed can be found in this article

Kamran Khatti
  • 2,402
  • 14
  • 22
4

Something I ran into that wasn't apparent from a first reading of the tutorial and docs was the idea of multicasting.

Make sure you're aware that by default, multiple subscriptions will trigger multiple executions in an Observable. Multiple subscriptions to a single HTTP call Observable will trigger multiple identical HTTP calls unless you .share() (enable multicasting).

A promise forces you to deal with one thing at a time, unwrap its data, handle exceptions, has language support for cool things like async/await, and is pretty barebones otherwise.

An Observable has lots of bells and whistles, but you need to understand the power you're working with or it can be misused.

rpgFANATIC
  • 160
  • 2
  • 9
4

I see a lot of people using the argument that Observable are "cancellable" but it is rather trivial to make Promise "cancellable"

function cancellablePromise(body) {
  let resolve, reject;
  const promise = new Promise((res, rej) => {
    resolve = res; reject = rej;
    body(resolve, reject)
  })
  promise.resolve = resolve;
  promise.reject = reject;
  return promise
}

// Example 1: Reject a promise prematurely
const p1 = cancellablePromise((resolve, reject) => {
  setTimeout(() => resolve('10', 100))
})

p1.then(value => alert(value)).catch(err => console.error(err))
p1.reject(new Error('denied')) // expect an error in the console

// Example: Resolve a promise prematurely
const p2 = cancellablePromise((resolve, reject) => {
  setTimeout(() => resolve('blop'), 100)
})

p2.then(value => alert(value)).catch(err => console.error(err))
p2.resolve(200) // expect an alert with 200
Batiste Bieler
  • 199
  • 1
  • 6
4

Observables are often compared to promises. Here are some key differences:

Observables are declarative; computation does not start until subscription. Promises execute immediately on creation. This makes observables useful for defining recipes that can be run whenever you need the result.

Observables provide many values. Promises provide one. This makes observables useful for getting multiple values over time.

Observables differentiate between chaining and subscription. Promises only have .then() clauses. This makes observables useful for creating complex transformation recipes to be used by other parts of the system, without causing the work to be executed.

Observables subscribe() is responsible for handling errors. Promises push errors to the child promises. This makes observables useful for centralized and predictable error handling.

That is the most simplest difference that you may found on ANGULAR.IO docs. rest answer is given by most is correct at its own place

ankita kumari
  • 161
  • 1
  • 6
4
  1. a Promise is eager, whereas an Observable is lazy,
  2. a Promise is always asynchronous, while an Observable can be either synchronous or asynchronous,
  3. a Promise can provide a single value, whereas an Observable is a
    stream of values (from 0 to multiple values),
  4. you can apply RxJS operators to an Observable to get a new tailored stream.
Yogesh Waghmare
  • 496
  • 3
  • 6
3

The basic difference between observable and promises are:

enter image description here

Chirag
  • 509
  • 1
  • 6
  • 15
  • 2
    Please **[edit]** your post and show the actual content as text instead of screenshots. Others can't copy and paste from your images. [See here](https://meta.stackoverflow.com/a/285557/1402846) for details. Thank you. – Pang May 03 '19 at 01:40
3
  1. Promises are focused only for single values or resolves, observables are stream of data.

  2. Observables can be canceled but promises can't be canceled.

The least known one, atleast to me is

  1. Promises are always of asynchronous nature, but observables can be both synchronous and asynchronous.

If you want to read about it in detail, I wrote a blog post following on this answer. https://vikky.dev/observables-vs-promises

Vignesh
  • 904
  • 1
  • 14
  • 34
3

Promise

A Promise handles a single event when an async operation completes or fails.

Note: There are Promise libraries out there that support cancellation, but ES6 Promise doesn't so far.

Observable

An Observable is like a Stream (in many languages) and allows to pass zero or more events where the callback is called for each event.

-1

There are lots of answers on this topic already so I wouldn't add a redundant one.

But to someone who just started learning Observable / Angular and wonders which one to use compare with Promise, I would recommend you keep everything Observable and convert all existing Promises in your project to Observable.

Simply because Angular framework itself and it's community are all using Observable. So it would be beneficial when you integrate framework services or 3rd party modules and chaining everything together.


While I appreciate all the downvotes but I still insist my opinion above unless someone put a proper comment to list a few scenarios that might still be useful in your Angular project to use Promises over Observables.

Of course, no opinion is 100% correct in all cases but at least I think 98% of the time for regular commercial projects implemented in Angular framework, Observable is the right way to go.

Even if you don't like it at the starting point of your simple hobby project, you'll soon realise almost all components you interact with in Angular, and most of the Angular friendly 3rd party framework are using Observables, and then you'll ended up constantly converting your Promise to Observable in order to communicate with them.

Those components includes but not limited to: HttpClient, Form builder, Angular material modules/dialogs, Ngrx store/effects and ngx-bootstrap.

In fact, the only Promise from Angular eco-system I dealt with in the past 2 years is APP_INITIALIZER.

Xinan
  • 2,344
  • 12
  • 17
-1

Observables and Promises are helping us to work with the asynchronous functionalities in JavaScript/typescript. They are very similar in many cases, however, there are still some differences between them.

enter image description here

FAISAL
  • 305
  • 3
  • 4
  • 1
    Please **[edit]** your post and show the actual text instead of screenshots. Others can't copy and paste from your images. [See here](https://meta.stackoverflow.com/a/285557/1402846) for details. Thank you. – Pang Dec 14 '18 at 04:37
  • Except that not code but plain info, so i think it's okay to post it as an image – Alator Apr 19 '19 at 10:10
  • 1
    stop copy pasting from Kudvenkat's youtube videos. Downvote from me! :) – Pratik May 19 '19 at 17:57