Promises vs Observables vs Subjects
Published in
3 min readOct 13, 2023
Let’s explore Promises, Observables, and Subjects in RxJS in greater detail, including examples for each concept.
Promises:
Promises are a fundamental part of JavaScript, providing a way to handle asynchronous operations. A Promise represents a value which might be available now, or in the future, or never.
Characteristics of Promises:
- Single Value: Promises represent a single value that will be resolved or rejected.
- Immutable State: Once a Promise is resolved or rejected, its state cannot be changed.
- Error Handling: Promises have built-in error handling through
.catch()
ortry...catch
blocks.
Example:
Consider an asynchronous operation like fetching data from an API.
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Data fetched successfully!');
}, 2000);
});
}
fetchData()
.then(data => {
console.log(data); // Output: Data fetched successfully!
})
.catch(error => {
console.error(error);
});
In this example, fetchData()
returns a Promise that resolves after 2 seconds, simulating an asynchronous operation.