Async/Await
Intro to Asyncawait
Async/await is syntactic sugar over Promises that makes asynchronous code read
like synchronous code. It's the preferred way to write async code in modern
TypeScript.
type Playlist = { id: string; trackIds: Array<string> }
type Track = { id: string; title: string }
async function fetchPlaylist(id: string): Promise<Playlist> {
return { id, trackIds: ['t1', 't2'] }
}
async function fetchTracks(ids: Array<string>): Promise<Array<Track>> {
return ids.map((id) => ({ id, title: `Track ${id}` }))
}
async function loadPlaylist(id: string) {
const playlist = await fetchPlaylist(id)
const tracks = await fetchTracks(playlist.trackIds)
return { playlist, tracks }
}
Why Async/Await?
- Readability - Code reads top-to-bottom like synchronous code
- Error handling - Use try/catch like synchronous code
- Debugging - Stack traces are clearer
- Less nesting - Avoid callback hell
Async/await doesn't replace Promisesβit's built on top of them. Every async
function returns a Promise, and you can await any Promise.
In this exercise, you'll convert Promise chains to async/await, handle errors
properly, and add explicit Promise return types.