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:
- A Promise can only return a single value, either a resolved value or a rejected value.
- Once a Promise is created, it cannot be cancelled.
- Promises do not have built-in operators for transforming or combining multiple Promises.
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:
- An Observable can emit multiple values over time.
- Observables are lazy, meaning they do not start emitting values until they are subscribed to.
- Observables can be cancelled by unsubscribing from them.
- Observables have built-in operators for transforming, combining, and filtering values.
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
Promises
are suitable for handling one-time asynchronous operations that return a single value. They are commonly used for making HTTP requests and handling simple asynchronous tasks.Observables
are suitable for handling streams of values over time, such as user input events, web sockets, and animations. They are also useful for handling complex asynchronous operations that require chaining, combining, or transforming multiple values.
Feature | Promise | Observable |
---|---|---|
Definition | A placeholder for a single value that will be available in the future. | A stream of values that are emitted over time. |
Data Emission | Emits a single value or an error. | Emits multiple values (0, 1, or more) over time. |
Lazy vs. Eager | Eager: starts executing immediately when created. | Lazy: only starts emitting values when subscribed to. |
Cancellation | Not cancelable. Once started, it runs to completion. | Cancelable via unsubscription. |
Operations | Limited to then , catch , and finally . | Rich set of operators (map , filter , merge , etc.) through libraries like RxJS. |
Time | Resolves once, at a single point in time. | Works over time and can handle asynchronous streams. |
Error Handling | Handles errors using .catch() . | Errors propagate to subscribers and can be caught. |
Multicast/Unicast | Unicast: Each .then() call gets the same value. | Can be unicast or multicast depending on implementation. |
Example Use Cases | Fetching data from an API, async workflows. | Handling real-time data streams, user inputs, or event listeners. |