Observables and Promises help us handle data that comes later, like waiting for a message or a file. They let us work with things that take time without stopping everything.
Observable vs Promise mental model in Angular
Promise example: const promise = new Promise((resolve, reject) => { // do something async resolve('done'); }); promise.then(value => console.log(value)); Observable example: import { Observable } from 'rxjs'; const observable = new Observable(subscriber => { subscriber.next('first'); subscriber.next('second'); subscriber.complete(); }); observable.subscribe(value => console.log(value));
Promises handle one value or error and then finish.
Observables can send many values over time and can be stopped.
const promise = new Promise(resolve => { setTimeout(() => resolve('Hello from Promise!'), 1000); }); promise.then(msg => console.log(msg));
import { Observable } from 'rxjs'; const observable = new Observable(subscriber => { subscriber.next('First message'); setTimeout(() => subscriber.next('Second message'), 1000); setTimeout(() => subscriber.complete(), 1500); }); observable.subscribe({ next: msg => console.log(msg), complete: () => console.log('Done') });
const promise = fetch('https://api.example.com/data').then(res => res.json()); promise.then(data => console.log(data));
import { interval } from 'rxjs'; const observable = interval(1000); // emits numbers every second const subscription = observable.subscribe(num => console.log(num)); setTimeout(() => subscription.unsubscribe(), 3500);
This Angular component shows how a Promise gives one message after 2 seconds, while an Observable sends multiple messages over time and then finishes.
import { Component } from '@angular/core'; import { Observable } from 'rxjs'; @Component({ selector: 'app-root', template: ` <h1>Observable vs Promise Demo</h1> <button (click)="startPromise()">Start Promise</button> <button (click)="startObservable()">Start Observable</button> <div> <h2>Promise Result:</h2> <p>{{ promiseResult }}</p> </div> <div> <h2>Observable Results:</h2> <ul> <li *ngFor="let msg of observableResults">{{ msg }}</li> </ul> </div> ` }) export class AppComponent { promiseResult = ''; observableResults: string[] = []; private observableSubscription: any; startPromise() { this.promiseResult = 'Waiting...'; const promise = new Promise<string>(resolve => { setTimeout(() => resolve('Promise says hello!'), 2000); }); promise.then(msg => this.promiseResult = msg); } startObservable() { this.observableResults = []; const observable = new Observable<string>(subscriber => { subscriber.next('Observable message 1'); setTimeout(() => subscriber.next('Observable message 2'), 1000); setTimeout(() => subscriber.next('Observable message 3'), 2000); setTimeout(() => subscriber.complete(), 2500); }); this.observableSubscription = observable.subscribe({ next: msg => this.observableResults.push(msg), complete: () => this.observableResults.push('Observable complete') }); } }
Promises start immediately when created; Observables start when you subscribe.
Observables can be cancelled by unsubscribing; Promises cannot be cancelled once started.
Use Observables for streams of data, Promises for single async results.
Promises handle one future value or error.
Observables handle many values over time and can be stopped.
Choose based on whether you expect one or many results and if you need to cancel.
Practice
Observable and a Promise in Angular?Solution
Step 1: Understand the nature of Promise
APromiserepresents a single future value or error that will be resolved once.Step 2: Understand the nature of Observable
AnObservablecan emit multiple values over time and can be stopped or cancelled.Final Answer:
Promisehandles a single future value;Observablecan handle multiple values over time. -> Option BQuick Check:
Promise = single value, Observable = multiple values [OK]
- Thinking Promise can emit multiple values
- Believing Observable cannot be cancelled
- Confusing synchronous and asynchronous behavior
Solution
Step 1: Check Promise constructor syntax
The Promise constructor takes a function with two parameters:resolveandreject.Step 2: Verify correct usage to resolve with 42
Callingresolve(42)inside the function correctly resolves the Promise with 42.Final Answer:
const p = new Promise((resolve, reject) => resolve(42)); -> Option CQuick Check:
Promise constructor needs resolve and reject parameters [OK]
- Omitting reject parameter in Promise constructor
- Calling reject instead of resolve to return value
- Returning value directly without resolve
const obs = new Observable(subscriber => {
subscriber.next(1);
subscriber.next(2);
subscriber.complete();
});
obs.subscribe(value => console.log(value));What will be printed to the console?
Solution
Step 1: Analyze Observable emissions
The Observable emits two values: 1 and 2, then completes.Step 2: Understand subscription behavior
The subscriber logs each emitted value, so both 1 and 2 are printed.Final Answer:
1 2 -> Option AQuick Check:
Observable emits multiple values, all logged [OK]
- Assuming only first value is logged
- Thinking complete() emits a value
- Confusing Observable with Promise single value
const p = new Promise((resolve, reject) => {
setTimeout(() => resolve('done'), 1000);
});
p.then(result => console.log(result));
p.catch(error => console.error(error));
p.cancel();Solution
Step 1: Check Promise API for cancellation
Promises do not support cancellation; there is no cancel() method.Step 2: Identify error cause
Callingp.cancel()will cause a runtime error because cancel() is undefined.Final Answer:
Promises do not have a cancel() method, so calling it causes an error. -> Option AQuick Check:
Promise cancellation is not supported [OK]
- Thinking Promise supports cancel() like Observable
- Confusing resolve and reject usage
- Believing then() must come after catch()
Solution
Step 1: Identify need for multiple values over time
Fetching user data every 5 seconds means multiple values over time, which suits an Observable.Step 2: Understand cancellation requirement
Observables can be unsubscribed to stop receiving updates, fitting the need to stop on navigation.Final Answer:
Use an Observable that emits new user data every 5 seconds and unsubscribe on navigation. -> Option DQuick Check:
Multiple updates + cancel = Observable with unsubscribe [OK]
- Using Promise for multiple repeated values
- Assuming Promise supports cancel()
- Not unsubscribing Observable causing memory leaks
Ready to prove it?
Pass the test and this pattern moves unknown
