Angular: Observable v/s Promise
Ankush Goyal
Posted on November 27, 2024
Observables and Promises are both used to handle asynchronous operations in JavaScript, but they have some key differences:
Promises
- Single Value: Promises handle a single asynchronous event and return a single value (or error).
- Eager: Promises start executing immediately upon creation.
- Not Cancellable: Once a Promise is initiated, it cannot be cancelled.
-
Syntax: Uses
.then()
,.catch()
, and.finally()
for chaining operations.
Example:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Promise resolved!');
}, 1000);
});
promise.then((value) => {
console.log(value);
});
Observables
- Multiple Values: Observables can emit multiple values over time.
- Lazy: Observables do not start emitting values until they are subscribed to.
- Cancellable: Subscriptions to Observables can be cancelled, stopping the emission of values.
-
Syntax: Uses
.subscribe()
to handle emitted values, errors, and completion.
Example:
import { Observable } from 'rxjs';
const observable = new Observable((subscriber) => {
subscriber.next('First value');
setTimeout(() => {
subscriber.next('Second value');
subscriber.complete();
}, 1000);
});
const subscription = observable.subscribe({
next(value) {
console.log(value);
},
complete() {
console.log('Observable complete');
}
});
// To cancel the subscription
subscription.unsubscribe();
When to Use Each
- Use Promises when you need to handle a single asynchronous operation.
- Use Observables when you need to handle multiple asynchronous events or values over time, and when you need more control over the data stream (e.g., cancellation, transformation).
Thank you for reading!
I hope you found this article helpful and informative. If you enjoyed it or learned something new, feel free to share your thoughts in the comments or connect with me.
If you'd like to support my work and help me create more content like this, consider buying me a coffee. Your support means the world and keeps me motivated!
Thanks again for stopping by! π
π πͺ π
π©
Ankush Goyal
Posted on November 27, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
angular How ViewEncapsulation Works in Angular: The Shadow DOM, Emulated, and None Modes
November 11, 2024
angular Step-by-Step Guide to an Angular Expandable and Collapsible Sidebar with Icons
November 22, 2024