What is the difference between a Promise and Observable?


The pimple-simple explanation for dummies like me.

Nail this and you'll leap-frog your competence as an Angular developer.

What is the difference between a Promise and an Observable?

And how do you master the difference without bending your mind into pretzel knots?

In a way that's as simple and plain as the nose on your face?

so-confused

By the way, did you know you're not the only one with questions about Promises and Observables?

I recently noticed that there's a question on StackOverflow that's received thousands of votes from other folks wondering what the difference is between a Promise and Observable.

difference-between-promise-and-observable

Interesting, eh?

Reactive and asynchronous programming have a way of tripping us developers and sending us sprawling to the ground - at least that's been my case. I've made and watched other developers make many mistakes and false assumptions that later turned around and bit us HARD.

😬 😬 😬

ouch

Not to mention the confusion between asynchronous programing and reactive programming.

Yes buddy, you're not the only one roaming around and getting confused in this new world of Observables and Promises.

It starts with a story...

Awhile ago I applied to become a GDE (Google Developer Expert).

Joining the GDE program was never really something I dreamed of doing but after an email conversation with another GDE I figured why not try it - so I applied.

After my application was accepted I had to pass two more interviews before being accepted as a GDE.

  1. Community Interview
  2. Technical Interview

I was told that the community interview would be simple. In other words, this wasn't going to be a technical discussion but more of a discussion to see whether I'm a good fit or not. So I was supposed to sit back and relax because this wasn't going to be a difficult thing, or so I was told.

"Doesn't sound bad", I thought. I figured I could brush up before the technical interview and pass with flying colors.

Boy oh boy. Was I wrong!!!

On our scheduled interview we first began chatting about my contributions, etc... to the Angular community. As well as why I had applied and small talk like that.

I was pretty confident I was crushing it...

Until...

The interviewer...

Popped the question.

"How would you explain the difference between a Promise and an Observable to a novice?"

I blinked.

"Uh..."

"Um... Well..."

"Uh..."

"I guess I've never been asked that question before. Lemme think... Um..."

Boy, oh boy. I was screwed.

oh

I managed to stumble through the question like a wobbly drunkard at 2 A.M. trying to find his way home but I was pretty sure that my chances of becoming a GDE were shredded. Of course, I can apply sometime again in the future.

But for now, why not focus on learning what the difference is between a Promise and an Observable, eh? πŸ˜†

So, first things first.

What is a Promise?

A Promise is an object the represents the eventual success or failure of an asynchronous operation. As well as it's return value.

Have you ever noticed how computer programming borrows a lot of terms from common language?

In this case, we're using the word promise which in common English language means a declaration that something will or will not be done according to the dictionary.

When we talk about a promise in JavaScript we're talking about an asynchronous operation that has been promised. This means that the JavaScript promise is a promised operation that has various states such as...

  • Created
  • Pending
  • Success
  • Error

The JavaScript Promise is the backbone of asynchronous programming in JavaScript. It allows us to queue asynchronous tasks as a Promise and handle other stuff while we wait for the promise to complete.

What is an Observable?

But what about the Observable?

According to the RxJS documentation an Observable is...

The manifestation of a consumer. A type that may have some (or all) handlers for each type of notification: next, error, and complete. Having all three types of handlers generally gets this to be called an "observer", where if it is missing any of the notification handlers, it may be called a "partial observer".

Wait, what? I'm confused.

so-confused

Back to the dictionary, we'll notice that the word observable means capable of being or liable to be observed; noticeable; visible; discernible.

Hum. πŸ˜” πŸ˜” πŸ˜”

The word observable comes from the word observe.

Observe: to see, watch, perceive, or notice.

Interesting.

So first, an Observable is not the same thing as a Promise. They're two different beasts.

beast

Let me see if I can explain this in pimple-simple terms without twisting our brains into pretzel knots.

An Observable is a listener that subscribes to an event emitter and fires every time a new event is emitted.

In other words, an Observable observes whatever you tell it to and then fires when a specified condition is met.

Like this example - we observe for a specific button click and then log to the console.

var button = document.querySelector('button');
Rx.Observable.fromEvent(button, 'click').subscribe(() => console.log('Button clicked'));

Make sense buster?

Observables and Promises are really not that complicated - if you listen to great teachers like me. 😜

Which leads us to the most important question in this article.

What is the difference between an Observable and a Promise?

Imagine you win a ticket to the world's best Angular conference - ng-conf.

You pack your bags, hop on a plane and head to the conference location. When you show up for the first talk you discover that the father of Angular - MiΕ‘ko Hevery himself - is giving the very first talk.

So what are you going to do?

  • Pop in for a second, catch only one word of his talk and leave?
  • Or will you sit down and "observe" every thing he's saying and showing?

Obviously, if you're like me, you would do the latter, right?

In other words, if you were like a JavaScript Promise you would pop in, catch a word and then "complete" or leave.

But since you've invested a lot to be at the Angular conference you're going to act like an Observable and observe everything that MiΕ‘ko Hevery is saying.

So you're sitting there listening and suddenly your phone buzzes. You look down at it and completely zone out for 36 seconds until all of a sudden you remember that the father of Angular is speaking and you'd better pay attention.

What have you just done?

You unsubscribed from his talk. But as soon as you realized that you had gotten distracted by your phone you put it away and now you're acting like a "good" Observable.

But let's go further. What are some more differences between the Observable and the Promise?

  • An Observable is lazy and a Promise is immediately executed

A Promise is eager. As soon as you define it, the function inside will start running.

An Observable is lazy. Nothing happens until you subscribe to it and then something could happen each time an observer subscribes (hot observable). Even though we define the same values for our Observables and Promises the output of each block will be different because they are executed at different times!

  • Promises can only resolve once where as an Observable can resolve multiple times, until the Observer quits or until it decides to unsubscribe.

It's a pretty straightforward, modern concept: an observable is just what it sounds like. It can only be resolved once. A promise is much more flexible. Multiple times you can call its .then() function to check if your promise has been resolved yet or not, and then use that result later in whatever method you want to handle the task.

  • Observables help with concurrency where as promises handle one thing at a time.

When you’re writing JavaScript, it’s important to consider what happens when you make an asynchronous call. In other words, are you going to get back one result or multiple results? Are you going to be able to cancel the call?

The answer is that promises handle one-time events and data streams, whereas observables handle asynchronous events that emit lots of values over time. In a nutshell: Promises are for events that happen once. Observables are for handling events multiple times (or none at all) over time.

And of course, an Observable has so many other features that a Promise doesn't have like transformation and filtering operators, etc...

Which one should I use?

When you have a single asynchronous event to observe, use a Promise. If you have multiple events in the future that may or may not occur, use an Observable.

Observables help with concurrency, as well as handling events coming from things like mouse clicks or timer events. Promises handle one thing at a time meaning that they're better for dealing with situations where you want to make sure something only happens once.

Promises are good for one-off events and Observables are good for streams of data.

Time to unsubscribe? Or call finished?

So to wrap this up...

Remember, the significant difference between Promises and Observable is that an Observable can subscribe to multiple values over time, while a Promise emits only a single value.

Which do you prefer to use - an Observable or a Promise? Let me know in the comments below.

signature

Angular Consultant