Difference between Promise and Observable

Promise and Observable are used to handle the asynchronous operation.

What is Promise?

Promise is a native to a JavaScript so you have no need to install it in your code file.

What is Observable?

Observable is a part of Rxjs library so if you want to use then firstly install rxjs library after that import into your Angular ts file.


import { Observable } from 'rxjs';

Difference between Promise and Observable

Promise
1) Promise execute immediately when we create.
Example:-


const promise = new Promise(resolve =>{
      console.log("Call Promise");
    });

Output into the browser’s console

Call Promise

Observable
1) Observable is a lazy when does not start until subscribe.


 const observable = new Observable(sub => {
      console.log("observable");
});

Output into the browser’s console
No one data will be show

Promise
2) Promise emits only single value. so if you implement multiple resolve to get the value then first resolve value will be show.


  const promise = new Promise(resolve =>{
        resolve("call promise1");
        resolve("call promise2");
        resolve("call promise3");
    });

To listen the promise use then keyword.


 promise.then(result => console.log(result));

Output into the browser’s console

call promise1

Observable
2) Observable returns multiple values.


     const observable = new Observable(sub => {
         sub.next("Observable1 is working");
         sub.next("Observable2 is working");
         sub.next("Observable3 is working");
}
observable.subscribe(result=> console.log(result);

Output into the browser’s console

Observable1 is working
Observable2 is working
Observable3 is working

Promise
3) Promise can not be cancel after create.

Observable
3) Observable can be cancel by using unsubscribe() method

Promise
4) Promise does not have operator.
Observable
4) Observable has rxjs operator like map, filter etc.