Promises vs Observables vs Subjects

Sumit kumar Singh
Frontend Weekly
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:

  1. Single Value: Promises represent a single value that will be resolved or rejected.
  2. Immutable State: Once a Promise is resolved or rejected, its state cannot be changed.
  3. Error Handling: Promises have built-in error handling through .catch() or try...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.

--

--

Sumit kumar Singh
Frontend Weekly

YouTube: https://shorturl.at/8zZ4B Linkedin: https://shorturl.at/TeLw7 📚 HTML, Angular, React, and JavaScript 🧑‍💻 Tips & tricks on Web Development