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?
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?
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.
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.
HTTP
requests. Basically, we only want to hit it once the user has stopped typing instead of with every keystroke.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
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:
observable:
Also, I've created the graphical image for you below to show the differences visually:
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?
Promises
Observables
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
Promises and Observables both handle the asynchronous call only.
Here are the differences between them:
Observable
Promise
Emits only a single value at a time
Calls the services without .then and .catch
Cannot be canceled
Does not provide any operators
Even though this answer is late, i have summarized the differences below,
Observable:
function
that takes an observer
and returns a function Observer: an object with next, error.
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
function to handle next value
,errors and
end of stream(ui events,http responses,data with web sockets).multiple values
over timecancel-able/retry-able
and supports operators such as map,filter,reduce
etc.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 rangePromise:
A promise represents a task that will finish in the future;
Promises become resolved by a value
;
Promises get rejected by exceptions;
Not cancellable
and it returns a single value
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
;
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.
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.
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.
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.
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:
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.
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
const promise = new Promise(resolve => {
setTimeout(() => {
resolve("Hello from a Promise!");
}, 2000);
});
promise.then(value => console.log(value));
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.
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
Observable
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:
Observable:
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.
Short answer :
Observable is better, it has all Promises features plus extra features.
Long answer:
Promises:
Observable:
Below are some important differences in promises & Observables.
Promise
Observable
For better understanding refer to the https://stackblitz.com/edit/observable-vs-promises
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
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);
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, it has much possibilities than promises.
Usage:
it has more possibilities like map, filter, pipe, map, concatMap etc
In a nutshell, the main differences between a Promise and an Observable are as follows:
a more detailed can be found in this article
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.
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
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
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.
Promises are focused only for single values or resolves, observables are stream of data.
Observables can be canceled but promises can't be canceled.
The least known one, atleast to me is
If you want to read about it in detail, I wrote a blog post following on this answer. https://vikky.dev/observables-vs-promises
Promise: is an ES6 feature that deals with async code which executes immediately on the creation that can only emit a single value at the time and are not cancelable , with modern applications and the complexity of the functionality needs , it will be necessary to implement complex code, if in the case we are dealing to execute many promises at the same time, or filter before execution or make some transformation :
myPromise.then((resolvedValue) => {
console.log(resolvedValue);
}, (error) => {
console.log(error);
});
Observable: is an Object provided b the Rxjs library that helps us to work with reactive programming in js applications, which provides chaining and subscription to handle complex applications having the advantage to be cancelable , providing many values at the same time, in addition, we can benefit of applying chaining of other operators like retry()
, map()
, filter()
, switchMap()
, etc .. which helps to deal with complex use cases and heavy user interfaces
Example instant search :
search(terms: Observable<string>) {
return terms.pipe(
debounceTime(400),
distinctUntilChanged(),
switchMap((term) => this.searchEntries(term))
);
}
Example many APIS calls in parallel :
let character = this.http.get('https://jsonplaceholder.typicode.com/todos');
let characterHomeworld = this.http.get(
'https://jsonplaceholder.typicode.com/posts'
);
forkJoin([character, characterHomeworld]).subscribe((results) => {
console.log('result °', results[0]);
console.log('result 1', results[1]);
});
One more difference: Global vs Imported
Promise is a Standard built-in object, You can use it directly, check the browser support here.
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('ready with out any installation');
}, 300);
});
myPromise
.then(value => { console.log(value) })
.catch(err => { console.log(err) });
Observable, Reactive Extensions for JavaScript need RxJS installation & import before use
import { Observable } from 'rxjs';