Observables and Promises are both used in asynchronous programming in JavaScript, but they have some fundamental differences:
Promises:
- Single Value: Promises represent a single value that will be resolved or rejected at some point in the future.
- Once Settled: A promise is settled once, meaning it can either be resolved with a value or rejected with a reason for failure.
- Static: Promises are static; once created, their state cannot be changed.
- No Cancellation: Once a promise is created, it cannot be canceled.
Example of a Promise:
const myPromise = new Promise((resolve, reject) => {
// Asynchronous operation
setTimeout(() => {
resolve('Operation completed'); // Resolving the promise with a value
// reject(new Error('Operation failed')); // Rejecting the promise with an error
}, 1000);
});
myPromise.then((result) => {
console.log(result); // Output: Operation completed
}).catch((error) => {
console.error(error); // Output: Error: Operation failed
});
Observables:
- Multiple Values: Observables represent a stream of values that can be emitted over time.
- Lazy Execution: They are lazy; they don't execute until someone subscribes to them.
- Can Emit Errors: Observables can emit multiple values, including errors.
- Can be Cancelled: They can be canceled by unsubscribing, allowing for cleanup.
Example of an Observable:
import { Observable } from 'rxjs';
const myObservable = new Observable(observer => {
let counter = 0;
const interval = setInterval(() => {
observer.next(counter++); // Emitting values in an interval
// if (counter > 5) observer.error('Something went wrong'); // Emitting an error
}, 1000);
return () => {
clearInterval(interval); // Cleanup logic on unsubscription
};
});
const subscription = myObservable.subscribe(
value => console.log(value), // Output: 0, 1, 2, 3, 4, 5...
error => console.error(error), // Output: Something went wrong
() => console.log('Complete') // Output when the observable completes
);
// To unsubscribe and stop receiving values
// subscription.unsubscribe();
In essence, Promises deal with a single future value (success or failure), while Observables handle a sequence of values that can arrive asynchronously over time, allowing more flexibility in handling streams of data or events. Observables also offer additional features like cancellation and handling multiple values/errors efficiently.