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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Promise
A
Promisehandles a single event when an async operation completes or fails.Note: There are
Promiselibraries out there that support cancellation, but ES6Promisedoesn’t so far.Observable
An
Observableis like aStream(in many languages) and allows you to pass zero or more events where the callback is called for each event.Often
Observableis preferred overPromisebecause it provides the features ofPromiseand more. WithObservableit doesn’t matter if you want to handle 0, 1, or multiple events. You can utilize the same API in each case.Observablealso has the advantage overPromiseto be cancellable. If the result of an HTTP request to a server or some other expensive async operation isn’t needed anymore, theSubscriptionof anObservableallows you to cancel the subscription, while aPromisewill eventually call the success or failed callback even when you don’t need the notification or the result it provides anymore.While a
Promisestarts immediately, anObservableonly starts if you subscribe to it. This is why Observables are called lazy.Observable provides operators like
map,forEach,reduce, … similar to an arrayThere are also powerful operators like
retry(), orreplay(), … that are often quite handy. A list of operators shipped with rxjsLazy execution allows you to build up a chain of operators before the observable is executed by subscribing, to do a more declarative kind of programming.
Both
PromisesandObservablesprovide 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.
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.
The demo will simply consist of two files:
app.tsandwikipedia-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.tsWe are injecting the
Jsonpservice to make a GET request against the Wikipedia API with a given search term. Notice that we calltoPromisein order to get from anObservable<Response>to aPromise<Response>. Eventually end up with aPromise<Array<string>>as the return type of our search method.app.tsThere is not much of a surprise here either. We inject our
WikipediaServiceand expose its functionality via a search method to the template. The template simply binds to keyup and callssearch(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
*ngForloop 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’sformControldirective. To use this directive, we first need to import theReactiveFormsModuleinto our application module.app.tsOnce imported, we can use formControl from within our template and set it to the name “term”.
In our component, we create an instance of
FormControlfrom@angular/formand expose it as a field under the name term on our component.Behind the scenes, term automatically exposes an
Observable<string>as propertyvalueChangesthat we can subscribe to. Now that we have anObservable<string>, overcoming the user input is as easy as callingdebounceTime(400)on ourObservable. This will return a newObservable<string>that will only emit a new value when there haven’t been coming new values for 400 ms.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
distinctUntilChangedoperator right after we calleddebounceTime(400)