Observable and Promise in JavaScript

 

Promise

  • Represents a single asynchronous value that will be available once in the future.
  • Either resolves successfully or rejects with an error.
  • Once settled (resolved/rejected), the result is immutable — it cannot emit further values.
  • Eagerly starts executing immediately upon creation.
  • Can be chained with .then().catch(), and .finally().
  • Commonly used for single async operations, like fetching data once.

Example:

const promise = new Promise((resolve) => {
  setTimeout(() => resolve("Done!"), 1000);
});

promise.then(result => console.log(result)); // Prints "Done!" after 1 second

Observable

  • Represents a stream of multiple asynchronous values over time (zero or more).
  • Can emit many values over time, not just one.
  • Supports cancellation and lazy execution — it only starts emitting when subscribed.
  • Can be subscribed to using .subscribe() and unsubscribed anytime.
  • Provides powerful operators (map, filter, debounce, etc.) for handling streams.
  • Commonly used with libraries like RxJS for handling complex async data streams (UI events, WebSocket messages, etc.).

Example:

import { Observable } from 'rxjs';

const observable = new Observable(subscriber => {
  subscriber.next("First value");
  setTimeout(() => subscriber.next("Second value"), 1000);
  setTimeout(() => subscriber.complete(), 2000);
});

observable.subscribe({
  next: val => console.log(val),
  complete: () => console.log("Completed")
});

Summary of Differences

FeaturePromiseObservable
ValuesSingle valueMultiple values over time
ExecutionEager (starts immediately)Lazy (starts on subscription)
CancellationNot cancellableCan be cancelled (unsubscribe)
UsageSimple async operationsEvent streams, complex async flows
Handling.then().catch().subscribe() + operators

Vikash Chauhan

C# & .NET experienced Software Engineer with a demonstrated history of working in the computer software industry.

Post a Comment

Previous Post Next Post

Contact Form