In this post we will see the difference between Observables and Promises .
Observable vs Promises
To handle asynchronous data either Promises or Observables can be used.
Promises can be executed immediately.
Observables are lazy. They are executed only after subscription. Subscrition to Observables are done through subscribe() method.
Observables are based on publisher subscriber concept. A consumer has to manually subscribe to Observables to receive data.
Observables subscription can be cancelled and Promises are not cancellable.
Within Observables subscribe() method, exception can be handled, but promises push errors to the child.
Promises emits only a single value. Observables emits stream of values.
The subscribe() method takes three methods as parameters.
Parameters
next
error
complete
next is called for each values emitted by Observable. when a second value is emitted the next is called again.
when there is an error, the error method is called.
complete is used to notify the successful completion.
Promise has a then() method which takes two functions resolve() and reject()
resolve() When an asynchronous code is executed successfully resolve() method should be called.
reject() When an asynchronous code has an error reject() function should be called.
Promise Example
const promise = new Promise(resolve => {
setTimeout(() => {
resolve('Promise executed in 1 second!');
}, 1000);
});
promise.then(value => {
//result
console.log(value);
});
Observable Example
const observable = new Observable(observer => {
setTimeout(() => {
observer.next('Emitted Value 1');
observer.next('Emitted Value 2');
observer.next('Emitted Value 3');
observer.next('Emitted Value 4');
}, 1000);
});
promise.subscribe(value => {
console.log(value);
});
If you see the above example, Observable emits multiple values. Whereas in Promise it can emit only one value, that is handled by resolve.