Both Observables and Promises are used for handling asynchronous operations in JavaScript, but there are some differences between them.
Promises represent a single future value that will be resolved at some point. They have three states: pending, fulfilled, or rejected. Promises are consumed using the .then() and .catch() methods to handle the fulfillment or rejection of the promise.
Here’s an example of a Promise:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Hello, world!");
}, 1000);
});
promise
.then((result) => {
console.log(result); // logs "Hello, world!" after 1 second
})
.catch((error) => {
console.error(error);
});
Observables, on the other hand, represent a stream of values that can be emitted over time. Observables can emit multiple values, and they can also emit errors. Observables are consumed using the .subscribe() method, which takes three callbacks: one for each emitted value, one for errors, and one for the completion of the observable.
Here’s an example of an Observable:
const { Observable } = rxjs;
const observable = new Observable((subscriber) => {
setTimeout(() => {
subscriber.next("Hello");
}, 1000);
setTimeout(() => {
subscriber.next("World");
}, 2000);
setTimeout(() => {
subscriber.complete();
}, 3000);
});
observable.subscribe(
(value) => console.log(value),
(error) => console.error(error),
() => console.log("Complete")
);
In summary, Promises are used for handling a single future value, while Observables are used for handling a stream of values over time. Promises are consumed using .then() and .catch(), while Observables are consumed using .subscribe().