Promises in Angular
π Promises in Angular – The Complete Beginner’s Guide (with Examples)
π Introduction
In modern Angular development, handling asynchronous operations is essential. Whether you're fetching data from an API, loading files, or wrapping browser-native APIs, Promises offer a clean and readable way to deal with one-time asynchronous operations.
This guide explains:
- What Promises are
- How they compare with Observables
- Real-world examples using
.then()andasync/await - When to use Promises vs Observables in Angular
π Table of Contents
- π What is a Promise?
- π Promise Lifecycle
- ✨ Key Features
- π Syntax
- π» Example 1: Fetch
- π» Example 2: setTimeout
- π Promises vs Observables
- π― When to Use Promises
- π¦ Angular Service Example
- π Observable vs Promise
- ❓ FAQ
- ✅ Summary
π What is a Promise?
A Promise is a JavaScript object that represents the eventual success (fulfilled) or failure (rejected) of an asynchronous operation.
π Common use cases in Angular:
- ✅ One-time data fetches
- ✅ Wrapping browser APIs (e.g., Geolocation)
- ✅ Simple async service logic
✨ Key Features of Promises
Start → Promise Created (Pending)
↓
Resolve (Fulfilled) → .then()
↓
Reject (Error) → .catch()
✨ Key Features of Promises
- ✅ Single resolution – A Promise resolves once via
resolve()orreject() - ⏱ Eager execution – Promises begin execution as soon as created
- π« Not cancelable – Once started, runs to completion
- π§ Great with async/await – Improves code readability
π§Ύ Promise Syntax
myPromise
.then(response => console.log("Success:", response))
.catch(error => console.error("Error:", error))
.finally(() => console.log("Completed"));
π» Example 1: Fetch Data Using fetch()
While Angular’s HttpClient returns Observables, you can use native fetch() to work with Promises directly.
function fetchData(): Promise<string> {
return fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => {
if (!response.ok) throw new Error("Network response was not ok");
return response.json();
})
.then(data => `Title: ${data.title}`);
}
// ✅ Using .then()
function usingThen() {
fetchData()
.then(result => console.log("Using .then():", result))
.catch(error => console.error("Error:", error));
}
// ✅ Using async/await
async function usingAsyncAwait() {
try {
const result = await fetchData();
console.log("Using async/await:", result);
} catch (error) {
console.error("Error:", error);
}
}
π§ͺ Output:
- Using .then(): Title: sunt aut facere repellat provident occaecati
- Using async/await: Title: sunt aut facere repellat provident occaecati
π» Example 2: Simulate Async Operation with setTimeout
function fetchData(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => resolve("Data loaded"), 1000);
});
}
function usingThen() {
fetchData().then(result => console.log("Using .then():", result));
}
async function usingAsyncAwait() {
try {
const result = await fetchData();
console.log("Using async/await:", result);
} catch (error) {
console.error("Error:", error);
}
}
usingThen();
usingAsyncAwait();
π§ͺ Output:
- Using .then(): Data loaded
- Using async/await: Data loaded
π Promises vs Observables in Angular
| Feature | Promise | Observable |
|---|---|---|
| Emits multiple values | ❌ | ✅ |
| Lazy execution | ❌ | ✅ |
| Cancelable | ❌ | ✅ |
| Built-in operators (map etc) | ❌ | ✅ (RxJS) |
| Best for... | ✅ One-time tasks | ✅ Streams/data flows |
π― When Should You Use Promises?
- ✅ You need one-time async operations
- ✅ You work with browser-native APIs
- ✅ You prefer using async/await
- ✅ Simpler logic flow is sufficient
π¦ Real Angular Example: Service Returning a Promise
@Injectable({ providedIn: 'root' })
export class DataService {
getData(): Promise<string> {
return new Promise((resolve) => {
setTimeout(() => resolve("Data from service"), 1000);
});
}
}
// In Component:
constructor(private dataService: DataService) {}
ngOnInit() {
this.dataService.getData().then(data => console.log(data));
}
π Observable vs Promise with Angular HttpClient
✅ Using Observable (default):
this.http.get('url').subscribe(response => console.log(response));
π Convert to Promise:
this.http.get('url').toPromise().then(response => console.log(response));
⚠️ Note: As of Angular v16+, toPromise() is deprecated. Use lastValueFrom() from RxJS instead.
❓ Frequently Asked Questions
- Can Promises be cancelled?
No, once a Promise starts it cannot be cancelled. - When should I use Promises in Angular?
For one-time operations like API calls or using browser APIs. - Are Promises better than Observables?
Promises are simpler for one-off tasks, while Observables handle streams and reactive data better. - Should I use async/await or .then()?
Use async/await for cleaner, more readable code.
✅ Summary
- Promises simplify one-time asynchronous operations in Angular.
- Use
.then(),.catch(),.finally()orasync/awaitfor better flow. - Prefer Observables for streams, multiple values, and Angular HttpClient.
- Visualizing the Promise lifecycle helps understand its behavior.
- Choose the right tool—Promise or Observable—based on your specific use case.
Comments
Post a Comment