Any modern application will always need to have a way to be reactive. What this means is that your applications should be aware of data changes and updates from the user actions and react in an expected manner. For that reason, there are two key ways to approach this, and thus, you may think need to make the decision on javascript promise vs javascript observable.
This short tutorial tip will settle this argument for you. At the end of the tutorial, you will be wary of how to proceed the next time you encounter yourself with a javascript promise vs javascript observable dilemma.
First things first, to answer your question on which is better to use – javascript promise or javascript observable, the answer is simple, neither. It all depends on your intended use case. I may have burst your bubble, but at times, reality is often disappointing (Thanos – The Mad Titan). So, you should now be thinking about which is most appropriate for your use case, rather than javascript promise vs javascript observable.
I know you were here for a clear cut discsussion on javascript promise vs javascript observable, but just sit tight.
Now, the best way to continue is to understand what a javascript promise is and what a javascript observable is. So we now shift the mindset from javascript promise vs javascript observable to what each of these are, so that it is possible to make the right decision when it comes to which you should use.
But we will do this in very simple plain English – yes Javascript in plain English! Let’s answer these two questions:
1. What is a Promise
A promise is simply putting yourself out there and committing that once you are able to, you will do something.
You can also make a promise to yourself that as soon as you start working out, then you will stop eating junk food.
2. What / Who is an Observer
Think of an observer as someone who watches for changes as they happen and then they report back to the necessary authority.
You can be an observer of your own weight and take down notes each time you go into and out of the gym, so that you are subscribed to your weight changes and hence calculate the likes of your BMR etc.
So, having understood what a promise is and what an observer is, then now let’s directly map the above understanding onto javascript reactive programming context. So, let’s see:
1. What is a Javascript promise
A javascript promise is the declaration of a commitment that once data is available, you will provide it to the promised party and settle the debt of that promise. Once the debt is settled then that is it. This is done only once.
2. What is a Javascript observable
A javascript observable is the dedication that you will always provide data to the observing party every time the data is available. However, your ability to provide data to the subscribed party will be up to the point where the party does not need your data any more.
So, having had an understanding of what a javascript promise is and what a javascript observable is, then it is best to see example use cases on where to use either, and maybe a code sample for each use case.
Now let's see some examples on this javascript promise vs javascript observable tutorial.
Let’s say that you want to login your user, then once the user is logged in, you will welcome them with a nice notification message. We can use a simple promise here.
/**
*
* @param email
* @param password
*
* login user using their email and password
*/
function loginUser(
email: string,
password: string
) {
const resource = new Request(`https://your-backend-endpoint/login`)
const formData = new FormData();
formData.set('email', email);
formData.set('password', password);
return fetch(resource, {method: 'POST', mode: 'cors', body: formData}).then(
response => {
if (!response.ok) {
return Promise.reject('Invalid credentials!');
}
return response.json();
}
).then(response => {
return Promise.resolve(response);
})
}
/**
*
* @param email
* @param password
*
* hypothetically, when the user clicks the login button, pass in the value for
* email and password.
*/
function doLogin(email: string, password: string) {
loginUser(email, password).then(res => {
alert(`Hi there ${res.fullName}`)
}).catch(err => {
alert('Oooops! Invalid credentials provided')
});
}
Now lets take a look at the next option of this javascript promise vs javascript observable discussion.
So, once your user above is logged in, then let’s assume that they have a section where they need to add their leads for the day as phone numbers, and then have these displayed on the UI. The UI will subscribe to the numbers entered and then it will be updated to reflect these changes.
/**
* This is a mock hypothetical component, and for this case, we are using Angular.
*
* This will give you a better understanding on how powerful javascript observables are.
*/
@Component({
selector: 'app-leads-component'
})
export class LeadsComponent {
/**
* A list of leads
*/
private _myLeads: Array<ILead>;
/**
* A BehaviourSubject is an observable which is imported from RXJS.
*
* It makes it possible to populate your initial data, with something
* which you can present to the UI, and have it updated with time.
*/
public myLeads$: BehaviourSubject<Array<ILead>> = new BehaviourSubject<Array<ILead>>([]);
constructor(
private _yourBackendService: YourBackendService
) {}
/**
* when the component intialized
*/
ngOnInit() {
this._listenForLeadsFromBackend();
}
/**
* listen for the list of leads user currently has in their backend,
* and this will fetch the leads only once when the component is
* initialized.
*
* IF you want to have the event for new leads from the backend, then in
* that case, you will have to go the WebSocket way, which is out of the scope of this tutorial
*/
private _listenForLeadsFromBackend(): void {
this._yourBackendService.getLeads().subscribe(
/**
*
* @param leads
*
* here, update the list of your leads with the received leads from the server
* then set the next value for myLeads$ to your _myLeads
*/
(leads: Array<ILead>) => {
this._myLeads = leads;
this.updateMyLeadsObservable();
}
)
}
/**
*
* @param number
* @param name
*
* add a lead number by inputting it and then updating on the UI all
* the leads
*/
public addCustomerLeadNumber(number: string, name: string) {
this._myLeads.push(new Lead(number, name));
this.updateMyLeadsObservable();
}
/**
* common method for updating my leads observable
*/
public updateMyLeadsObservable(): void {
this.myLeads$.next(this._myLeads);
}
}
Clearly, you can see that the javascript observable comes in handy for those reactive programming features that are needed, albeit a bit more code is needed.
So, don’t think of javascript promise vs javascript observable any more, rather think of your use case.
So, you can now see that it is not a matter of javascript promise vs javascript observable, rather it is a matter of which is best for your use case.
So, the next time you want to have reactive programming on your code, then you can now comfortably choose between a javascript promise or a javascript observable.
Feel free to share this with your friend and help them out as well on the javascript promise vs javascript observable dilema.
Well, until the next article!