Skip to content

Difference between Promise and Observable in Angular

In Angular, both Promises and Observables are used to handle asynchronous operations.

While they are similar in some ways, they have some key differences that make them suitable for different use cases.

Promises

A Promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value.

It is a one-time operation that can either succeed or fail. Promises have the following characteristics:

Example

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

promise.then((value) => {
  console.log(value); // Output: Hello, World!
});

Observables

An Observable is a representation of a stream of values over time. It can emit multiple values asynchronously and can be cancelled.

Observables have the following characteristics:

Example

import { Observable } from 'rxjs';

const observable = new Observable((observer) => {
  let count = 0;
  const interval = setInterval(() => {
    observer.next(count);
    count++;
    if (count === 5) {
      observer.complete();
      clearInterval(interval);
    }
  }, 1000);
});

const subscription = observable.subscribe({
  next: (value) => console.log(value),
  complete: () => console.log('Complete!'),
});

// Output:
// 0
// 1
// 2
// 3
// 4
// Complete!

Summary

FeaturePromiseObservable
DefinitionA placeholder for a single value that will be available in the future.A stream of values that are emitted over time.
Data EmissionEmits a single value or an error.Emits multiple values (0, 1, or more) over time.
Lazy vs. EagerEager: starts executing immediately when created.Lazy: only starts emitting values when subscribed to.
CancellationNot cancelable. Once started, it runs to completion.Cancelable via unsubscription.
OperationsLimited to then, catch, and finally.Rich set of operators (map, filter, merge, etc.) through libraries like RxJS.
TimeResolves once, at a single point in time.Works over time and can handle asynchronous streams.
Error HandlingHandles errors using .catch().Errors propagate to subscribers and can be caught.
Multicast/UnicastUnicast: Each .then() call gets the same value.Can be unicast or multicast depending on implementation.
Example Use CasesFetching data from an API, async workflows.Handling real-time data streams, user inputs, or event listeners.