In Angular, for handling asynchronous data, either Promise & Observable is used. Both get and post method of Http & HttpClient return Observable and it converted to a promise by using toPromise() method. But where does the difference lie? Before throwing light on this, I would like to mention in brief about what is an Observable & a Promise:
A Promise was introduced in JavaScript ES6 version as a solution to a callback hell which occurs when callback functions are nested in other callbacks at one or more levels. Promise provide with a modern and powerful abstraction for writing asynchronous code in a better and a maintainable way.
An Observable is used in Angular as an interface to handle a variety of asynchronous callback operations, such as defining custom events that send observable output data from a child to a parent component. The HTTP module uses observables to handle AJAX requests and responses.
Now coming to the difference, promise emits a single value whereas an observable emits multiple values. So when we are handling a HTTP request, promise is manageable as a single response for the same request, but when we have to manage multiple responses for the same request then its ideal to choose observable over a promise.
To validate the difference further as discussed above, lets take some code snippets for both promise and observable as an example:
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
So in the above code snippets, the promise returns the very first value and hence ignores the remaining values, but an observable returns all the values and prints 1, 2 and 3 in the console.
After getting the gist of both promise and observable through code examples, I would like to mention some key differences between both:
Observables are lazy: they are not executed until we subscribe to them using the subscribe() method. Promises are not lazy: they execute immediately after creation.
Observables have subscriptions that are cancellable using the unsubscribe() method which stop the listener from receiving further values. Promises are not cancellable.
Observables deliver errors to the subscribers. Promises push errors to the child promises.
References:
Angular Docs