What is Async/Await?
Async/await is a modern way to handle asynchronous operations (like API calls) that makes your code look synchronous and easier to read.async→ Marks a function as asynchronous (it can wait for things)await→ “Wait here until this Promise resolves”
What is a Promise?
A Promise is like a “ticket” for a future value. Think of ordering food:- You order → You get a receipt (Promise)
- You wait → The promise is “pending”
- Food arrives → The promise is “resolved” with your food
Basic Syntax
Real Example: Fetching Products
From our project, here’s how we fetch products from an API:main.ts
The Fetch Flow
Without Async/Await (Old Way)
Before async/await, we used.then() chains:
With Async/Await (Modern Way)
Error Handling with Try/Catch
Usetry/catch to handle errors gracefully:
main.ts
When to Use Async/Await
Use async/await for operations that take time:- API calls (fetch, axios)
- Database queries
- File operations
- Timers (setTimeout as Promise)
- Any function that returns a Promise
Multiple Awaits (Sequential)
When you need things to happen in order:Multiple Awaits (Parallel)
When things can happen at the same time:Return Type: Promise<T>
Async functions always return a Promise:
Async Functions Can’t Run in Regular Functions
Common Pattern: Loading State Management
Combine async/await with enums for clean state management:Async/Await with Event Listeners
You can use async functions with event listeners:main.ts
loadProducts runs asynchronously.
Error Types and Instanceof
Check error types safely:main.ts
HTTP Status Codes
Common codes you’ll encounter:| Code | Meaning |
|---|---|
| 200 | OK (success) |
| 201 | Created (resource created successfully) |
| 400 | Bad Request (invalid data sent) |
| 401 | Unauthorized (need to log in) |
| 404 | Not Found (resource doesn’t exist) |
| 500 | Internal Server Error (server problem) |
main.ts
Default Parameters
Provide default values for parameters:main.ts
Next Steps
- Fetch API - Deep dive into fetch and HTTP requests
- DOM Manipulation - Update UI with fetched data
- Enums - Use enums to track async operation states