Promise vs Observable in Angular

In Angular, we can use either Promise or Observable for handling asynchronous data. Both get and post method of Http and HttpClient return Observable and it can be converted into Promise using toPromise() method. So, what’s the difference when they both are dealing with asynchronous data.

What actually the difference is?

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.
Let’s implement this with an example.

Promise

Output



 Observable

Output

So, in the above code snippet, I have created promise and observable of Promise and Observable type respectively. But, promise returns the very first value and ignore the remaining values whereas Observable return all the value and print 1, 2, 3 in the console.

Promise is not lazy while Observable is lazy. Observable is lazy in nature and do not return any value until we subscribe.

home.component.ts (Observable)

In above example we are not subscribing the observable, so we do not receive the data and even there would be a no network call for this service.

home.component.ts (Observable)

Here, we have subscribed our Observable, so it will simply return the data. But Promise returns the value regardless of then() method.

home.component.ts (Promise)

Observable is cancellable in nature by invoking unsubscribe() method, but Promise is not cancellable in nature.

Hope this is helpful and give you a basic understanding of how Promise differs from Observable. Please feel free to provide your suggestions 🙂


References:

http://csharp-video-tutorials.blogspot.com/2017/09/angular-promises-vs-observables.html
https://medium.com/@mpodlasin/promises-vs-observables-4c123c51fe13

knoldus-advt-sticker

2 thoughts on “Promise vs Observable in Angular

  1. Nice straight forward explanation of the difference between the 2. I would add that Observable has access to useful operators like map and forEach among others.

Leave a Reply

%d bloggers like this: