*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).
Top comments (0)