Linear Flow with Async/Await
Linear Flow
π¨βπΌ Let's refactor a Promise chain to use async/await. This will make the
code much more readable!
type Recipe = { id: string; title: string }
type Ingredient = { name: string }
async function loadRecipe(id: string): Promise<Recipe> {
return { id, title: 'Pancakes' }
}
async function loadIngredients(recipeId: string): Promise<Array<Ingredient>> {
return [{ name: `${recipeId}-flour` }]
}
async function loadCookingData() {
const recipe = await loadRecipe('r1')
const ingredients = await loadIngredients(recipe.id)
return { recipe, ingredients }
}
π¨ Open
and:
- Refactor
loadUserDatato useasync/awaitinstead of nested.then() - Keep the same return shape:
{ user, orders } - Await
fetchUser(), then awaitfetchOrders(user.id) - Export
loadUserData
Completion check:
await loadUserData() returns Alice (id: '1') and an
orders array whose first order has userId: '1'.π MDN - async function


