Promises and observables are both mechanisms used in JavaScript for handling asynchronous operations, but they have different characteristics and usage patterns.
Promises:
- Promise is an object representing the eventual completion or failure of an asynchronous operation and its resulting value.
- It has states: pending (initial state), fulfilled (operation completed successfully), or rejected (operation failed).
- A Promise can be created using the
new Promise()
constructor, taking a function withresolve
andreject
parameters. - It provides a cleaner way to write asynchronous code compared to callbacks, allowing chaining of
.then()
and.catch()
methods. .then()
is used to handle the resolved value, and.catch()
is used to catch any errors.- Promises are not cancellable, and once settled (fulfilled or rejected), they remain in that state.
Example:
function asyncOperation() {
return new Promise((resolve, reject) => {
// Asynchronous operation
if (/* operation successful */) {
resolve('Operation completed successfully');
} else {
reject('Operation failed');
}
});
}
asyncOperation()
.then(result => {
console.log(result); // Handle the successful result
})
.catch(error => {
console.error(error); // Handle errors
});
Observables:
- Observable is a pattern provided by the RxJS library for handling asynchronous data streams over time.
- It represents a sequence of values that arrive asynchronously over time.
- Observables can emit multiple values asynchronously, making them suitable for handling events, streams of data, or any asynchronous sequence.
- They offer powerful operators to transform, combine, and handle streams of data, making them more versatile compared to promises.
- Observables provide features like subscription and unsubscription, allowing better control over data streams. They can also be cancelled using subscriptions.
Example:
import { Observable } from 'rxjs';
const observable = new Observable(observer => {
// Emit values asynchronously
observer.next('First value');
observer.next('Second value');
// Complete the observable
observer.complete();
});
const subscription = observable.subscribe({
next: value => console.log(value), // Handle emitted values
error: error => console.error(error), // Handle errors
complete: () => console.log('Observable completed') // Handle completion
});
// Unsubscribe to stop receiving values
subscription.unsubscribe();
In essence, Promises are suitable for handling a single asynchronous operation, while Observables are more powerful for handling multiple asynchronous operations, streams of data, events, and providing better control and transformation capabilities over these streams.