Angular Features (A-1) --- Difference between Observable and Promise

Note: This article is published on 02/06/2025.

This series of articles will discuss the major feafures for Angular. The way to discuss could be AI in concept + Code Demo in StackBlitz | Instant Dev

Advanced:

 

A - Introduction

In Angular, both Observable and Promise are used to handle asynchronous operations, but they have key differences in behavior and use cases. The content of this article

  • Introduction
  • Differences

B - Differences:

The major differences will be discussed below:

1. Observable (RxJS)

  • Lazy Execution: Observables are not executed until they are subscribed to.
  • Multiple Values: They can emit multiple values over time (streams of data).
  • Cancellable: You can unsubscribe to stop receiving data.
  • Operators: Supports powerful operators like map, filter, retry, etc., for transformation and handling.
  • Better for Streams: Ideal for handling events, HTTP requests, WebSockets, etc.

 

2. Promise

  • Eager Execution: A promise starts executing immediately when created.
  • Single Value: A promise resolves only once and returns a single value.
  • Not Cancellable: Once started, a promise cannot be stopped.
  • No Operators: Limited chaining with .then() and .catch().
  • Simple Use Case: Best for one-time asynchronous tasks like fetching data once.

 

Example of Observable

import { Observable } from 'rxjs';

const observable = new Observable(observer => {
  observer.next("First value");
  observer.next("Second value");
  setTimeout(() => observer.next("Third value after 2s"), 2000);
  observer.complete();
});

observable.subscribe(value => console.log(value));

 

Example of Promise

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

promise.then(value => console.log(value));

 

Key Differences Summary

When to Use What?

  • Use Promise when you need a one-time async operation.
  • Use Observable when dealing with continuous data streams (e.g., real-time updates, WebSockets, HTTP polling, user events).

In Angular, Observables are commonly used with HttpClient and Forms due to their flexibility and cancellation ability.

 

References:

Up Next
    Ebook Download
    View all
    Learn
    View all