What is the difference between Promises and Observables?
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:
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’s 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. It sounds 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 parameters 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 a 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);
}
}
There is not much of a surprise here either. We inject our WikipediaService
and expose its 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 400 ms.
export class App {
items: Array<string>;
term = new FormControl();
constructor(private wikipediaService: WikipediaService) {
this.term.valueChanges
.debounceTime(400) // wait for 400 ms 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 application 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. I hope I can see some advanced use case in the future :)
Learn more
- https://angular-2-training-book.rangle.io/handout/observables/
- https://angular.io/tutorial/toh-pt6#observables
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?
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.