October 7, 2022 09:58 by
Peter
In this article, we are going to discuss the differences between Promises and Observable in angular programming. This article can be used by beginners, intermediates, and professionals.
We are going to cover,
Sync and Async
Promises vs Observables
Prerequisite
Basic knowledge of Angular
Basic knowledge of Promises and Observables.
Promises and Observables
We should understand Sync and Async first before we start on promises or observables.
In simple words,
Sync – Thread will wait for a response.
Async - The thread will request data in the background and the main thread will not wait for a response.
It means,
Sync code is blocking in nature hence Async programming comes in to picture.
Async programming is non-blocking and executes in the background without blocking the main thread.
Now a question comes in the mind, how will we have handled Async operations in Angular?
The answer would be using Promises or Observables.
Async operations can be handled in Angular either using promises or observables.
Now another question comes raised, what is the difference between them and when should we use what?
Differences between Promises and Observables
Promise provides the data once data will be ready. While Observables provides data in chunks.
Promise provide data whether someone is using it or not, but observables provide data only if someone request/subscribe to it.
A promise is native to JavaScript. Observables are part of RxJs not JavaScript.
A promise can emit only a single value while an observable can return multiple values.
Promise can’t cancel once created. Observables can be canceled using unsubscribe.
Promises don’t have operators. Observables provided operators like maps, filters, reduce, and retry, which are useful for complex scenarios.
Promises are eager. Observables are Lazy.
I hope you enjoy this article and find it useful.