To handle asynchronous data in Angular, we can use either Promise or Observable. Http and HttpClient's get and post methods both return Observable, which may be converted to Promise using the toPromise() method. So, when both are dealing with asynchronous data, what's the difference?
Observable emits several values, whereas Promise emits a single value. So, while Promise can handle a single response for the same request when handling an HTTP request, if there are numerous responses to the same request, we must utilise Observable. Yes, for the same request, Observable can handle many responses.
Let's put this into practise with an example.
const promise = new Promise((data) =>
{ data(1);
data(2);
data(3); })
.then(element => console.log(‘Promise ‘ + element));
const observable = new Observable((data) => {
data.next(1);
data.next(2);
data.next(3);
}).subscribe(element => console.log('Observable ' + element));
So, in the preceding code snippet, I constructed promise and observable, respectively, of the Promise and Observable types. Promise, on the other hand, returns only the first value and ignores the rest, whereas Observable returns all values and prints 1, 2, 3 in the console.
While Promise is not lazy, Observable is.
Observables are slow by nature, and they don't yield anything until we subscribe to them.
We may conceive of an observable as a stream that emits many values over time and calls the same callback function for each item emitted, thus we can use the same API to handle asynchronous data with an observable. if the data is sent as a single value or as a series of values over a period of time
Promise:
Observable:
Conclusion
In JavaScript, both Observables and Promises can be used to handle async activities. While an Observable can perform all of the functions of a Promise, the opposite is not true.