JavaScript Internals (521 Qs)•Part 6: Async Internals, Memory, Microtasks & Web APIs (329 - 403)
What are the differences between promises and observables
Some of the major difference in a tabular form
| Promises | Observables |
|---|---|
| Emits only a single value at a time | Emits multiple values over a period of time(stream of values ranging from 0 to multiple) |
| Eager in nature; they are going to be called immediately | Lazy in nature; they require subscription to be invoked |
| Promise is always asynchronous even though it resolved immediately | Observable can be either synchronous or asynchronous |
| Doesn't provide any operators | Provides operators such as map, forEach, filter, reduce, retry, and retryWhen etc |
| Cannot be canceled | Canceled by using unsubscribe() method |
Practical Code Example
javascript
// Promises vs Observables:
// Promise: Eager, returns a single value, not cancellable
const p = new Promise(resolve => resolve(42));
// Observable (RxJS): Lazy, streams multiple values over time, cancellable:
// const obs$ = new Observable(sub => { sub.next(1); sub.next(2); });
// const sub = obs$.subscribe(val => console.log(val));
// sub.unsubscribe(); // Can cancel subscription!