Skip to content

Difference between Promises and Observables

Published: at 08:44 AM (2 min read)

Promises and observables are both mechanisms for handling asynchronous operations in JavaScript, but they have some differences in terms of functionality and behavior.

A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. It is used to handle a single asynchronous event. When a promise is created, it is in one of three states: pending, fulfilled, or rejected. A pending promise is in an initial state, and it transitions to either fulfilled (resolved) or rejected (with an error) when the asynchronous operation completes. Promises are typically used with the .then() and .catch() methods to handle the fulfillment or rejection of the promise.

Example:

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("Operation completed successfully");
  }, 1000);
});

promise
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error);
  });

An Observable, on the other hand, is a more powerful and flexible construct introduced in the RxJS library, which extends the concept of promises. Observables represent a stream of values over time, allowing multiple asynchronous events to be handled. They can emit zero or more values and also notify about errors or the completion of the stream. Observables are used with various operators and subscription mechanisms to handle these events.

Example:

import { Observable } from "rxjs";

const observable = new Observable(observer => {
  setTimeout(() => {
    observer.next("First value");
  }, 1000);

  setTimeout(() => {
    observer.next("Second value");
  }, 2000);

  setTimeout(() => {
    observer.next("Third value");
    observer.complete(); // Notify completion
  }, 3000);
});

const subscription = observable.subscribe(
  value => console.log(value),
  error => console.error(error),
  () => console.log("Observable completed")
);

// Later, if necessary, you can unsubscribe
subscription.unsubscribe();

Differences between promises and observables:

FeaturePromisesObservables
Value SinglevalueStream of values
ExecutionEagerLazy
CancellationCan be canceledCan be canceled
Multiple subscriptionsNoYes
Error handlingPropagates errors to subscribersPropagates errors to subscribers

Promises:

Observables: