Why async/await in Angular ? π€
In Angular, many tasks, like fetching data from a server, can take time.
Normally, we use .subscribe() for handling these tasks, but it can get messy when we have to chain many steps or make the code look messy.
this.apiService.getData().subscribe(response => {
console.log('First API Response:', response);
this.apiService.getMoreData(response.id).subscribe(moreResponse => {
console.log('Second API Response:', moreResponse);
this.apiService.getDetails(moreResponse.detailId).subscribe(detailResponse => {
console.log('Third API Response:', detailResponse);
});
});
});
That's where async and await come in! They help us handle these tasks in a much cleaner, easier-to-read way.
import { firstValueFrom } from 'rxjs';
async fetchData() {
try {
const response = await firstValueFrom(this.apiService.getData());
console.log('First API Response:', response);
const moreResponse = await firstValueFrom(this.apiService.getMoreData(response.id));
console.log('Second API Response:', moreResponse);
const detailResponse = await firstValueFrom(this.apiService.getDetails(moreResponse.detailId));
console.log('Third API Response:', detailResponse);
} catch (error) {
console.error('Error occurred:', error);
}
}
With async/await, the code runs one step at a time without getting messy. Itβs easy to read, easy to fix if something goes wrong, and you can catch all errors in one place. Even though it works in the background, the code looks simple and clean.
What is async/await in Angular ? π
async is a keyword that we put in front of a function to tell it,
'Hey, this function is going to handle something that takes time.'
And await is used inside that function to wait for something to finish before moving to the next line of code.
async getData() {
const result = await this.http.get('https://api.example.com/users').toPromise();
console.log(result);
}
Here, await tells Angular to wait for the data before moving forward.
Without await, the code would keep running without waiting for the response, which might cause issues.
How to use async/await in Angular ? π§
Step 1: Add async to your function.
async ngOnInit() {
// your code here
}
Step 2: Use await inside the function to wait for something.
async ngOnInit() {
const data = await this.http.get('/api/data').toPromise();
console.log(data);
}
Step 3: If youβre using HttpClient, make sure to convert the Observable to a Promise (use .toPromise() or firstValueFrom()).
import { firstValueFrom } from 'rxjs';
async getData() {
const data = await firstValueFrom(this.http.get('/api/data'));
console.log(data);
}
Real-world example ? π
A practical use of async/await is in dependent dropdowns. For example, when a user selects a country, we need to fetch the states related to that country from the server.
Using async/await, we can wait for the states to load first, and only then populate the next dropdown, ensuring a smooth user experience without race conditions.
async onCountryChange(countryId: number) {
this.states = await this.locationService.getStatesByCountry(countryId);
}
Avoid mistakes when using async/await ? β οΈ
β Don't use await outside an async function.
ngOnInit() {
const user = await this.userService.getUser(); // β Error: 'await' is only valid in async functions
console.log(user);
}
β
Correct: Mark the function async
async ngOnInit() {
const user = await this.userService.getUser();
console.log(user);
}
β Don't mix await with subscribe() from RxJS. Use firstValueFrom() to convert Observables.
async fetchData() {
const data = await this.apiService.getData().subscribe(response => {
console.log(response);
});
}
β
Correct: Use firstValueFrom()
import { firstValueFrom } from 'rxjs';
async getData() {
const data = await firstValueFrom(this.apiService.getData());
console.log(data);
}
β Avoid unhandled try/catch. Always catch errors.
async fetchData() {
const data = await firstValueFrom(this.apiService.getData());
console.log(data); // β If API fails, app crashes without handling error
}
β
Correct: With try/catch (proper error handling)
async fetchData() {
try {
const data = await firstValueFrom(this.apiService.getData());
console.log(data);
} catch (error) {
console.error('Failed to fetch data:', error); // β
Graceful error handling
}
}
β Avoid using too many sequential await calls if they can be parallelized (performance hit).
async loadDashboard() {
const profile = await firstValueFrom(this.apiService.getProfile());
const notifications = await firstValueFrom(this.apiService.getNotifications());
const messages = await firstValueFrom(this.apiService.getMessages());
console.log(profile, notifications, messages);
}
β
Correct: Parallel await calls using Promise.all() (better performance)
async loadDashboard() {
const [profile, notifications, messages] = await Promise.all([
firstValueFrom(this.apiService.getProfile()),
firstValueFrom(this.apiService.getNotifications()),
firstValueFrom(this.apiService.getMessages())
]);
console.log(profile, notifications, messages);
}
Most asked interview question on async/await ? π―
πΉ Basic Questions
1οΈβ£ What is async/await in JavaScript/TypeScript?
π Async/await is syntax to handle promises in a cleaner and more readable way, making asynchronous code behave like synchronous code.
2οΈβ£ Why do we use async/await instead of .then()?
π Async/await avoids nested .then() chains and makes error handling with try-catch much simpler.
3οΈβ£ What does the async keyword do?
π It marks a function to always return a promise, even if it returns a simple value.
4οΈβ£ What does the await keyword do?
π It pauses the function execution until the awaited promise is resolved or rejected.
πΉ Angular-Specific Questions
5οΈβ£ Where would you typically use async/await inside an Angular application?
π In services while calling APIs, in component lifecycle methods (like ngOnInit), and during sequential operations like login β‘οΈ fetch profile β‘οΈ load dashboard.
6οΈβ£ Can we use async/await with HttpClient in Angular?
π Yes, but since HttpClient returns Observables, we often convert them to promises using .toPromise() (deprecated) or firstValueFrom() before using await.
7οΈβ£ Can we use async/await inside Angular services?
π Absolutely, services are a common place to write reusable async functions.
πΉ Practical Scenario-Based Questions
8οΈβ£ How would you handle multiple API calls using async/await?
π Either:
Wait one after another (sequentially)
Or use Promise.all() if APIs are independent and can run in parallel.
9οΈβ£ What happens if a promise fails inside an async function?
π It throws an exception, which we should catch using a try-catch block.
π Can we use async/await inside Angular interceptors?
π Yes, interceptors can be async if you return a promise that eventually resolves to an HTTP response.
πΉ Slightly Advanced Questions
1οΈβ£1οΈβ£ What are the drawbacks of async/await?
π
You cannot run operations in parallel easily without Promise.all().
If many awaits happen sequentially, it can slow down performance.
Error handling can become tricky if you await multiple things without a proper structure.
1οΈβ£2οΈβ£ Can you combine async/await and Observables?
π Yes!
We usually convert Observables to Promises if we want to use async/await.
Example:
typescript
Copy
Edit
await firstValueFrom(this.api.getData());
πΉ Bonus: Real-Life Use Case Questions
1οΈβ£3οΈβ£ Give one real-world example where async/await helped improve user experience in your project.
π Example:
Dependent dropdowns (country β states)
File upload before navigation
Token refresh before API calls
1οΈβ£4οΈβ£ How would you handle an API retry if the awaited call fails?
π Inside catch block, you can retry the call manually, or use retry strategies with services.
Top comments (0)