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
| Feature | Promise | Observable |
|---|---|---|
| Values | Single value | Multiple values over time |
| Execution | Eager (starts immediately) | Lazy (starts on subscription) |
| Cancellation | Not cancellable | Can be cancelled (unsubscribe) |
| Usage | Simple async operations | Event streams, complex async flows |
| Handling | .then(), .catch() | .subscribe() + operators |
Tags
JavaScript