javascript – What is the difference between Promises and Observables?

Question:

Can anyone explain to me the difference between Promises and Observables? I would like to understand the advantages and disadvantages of each. Which is more performant, which applies a best practice for development and so on. Thanks!

Answer:

Promises are native to ES6 and are great options especially compared to callback, we can live well with them. The then() methods, which can help solve a lot of problems, a good example would be to string them together like .then(…).then(…) . Methods like All() , Race() … lots of good possibilities using just Promise. However, still on ES7 we have Async/Await which only works with Promise!

To run an Observable , you need to use its Subscribe() method. Hi? It appears to be the same as then() , but it isn't! While in Observable you can perform all the programming with map() , catch() and everything before being executed, and then, when you trigger the Subscribe() oh yes… oh yes, it will be executed. Promise , after the return what is done with then() is treatment.

What I just said characterizes an Observable as Lazy , while Promise as eager . Don't confuse that word with Jaegers from Pacific Rim! 😮 P

Promise will run and use then() to handle it. Observable doesn't, it waits for Subscribe() where it actually executes and treats (reactive).

So is it a simple matter of preference? I do not think so! But being reactive, Observable would be my choice! In its posibilities like the Retry() function, which tries to reconnect or call your request again if you have connection swing issues, for example, it's a great feature. Promise does not have this reactive feature, however Promise is already Native ES6 , as stated at the beginning of this answer. We don't need to import anything, Observable is an alternative already coming from RxJS and needs to be imported, and very common for Angular 2+ dev.

Scroll to Top