Back

Async/Await with APIs

async/await makes async code read top to bottom like normal code. Mark the function async, then await each Promise. Use Promise.all to run independent requests at the same time instead of one after another.

async function loadUser(id: number) {
  const res = await fetch(`/api/users/${id}`)
  return res.json()
}

// One after another (slower)
const user = await loadUser(1)
const posts = await fetch("/api/posts").then((r) => r.json())

// At the same time (faster)
const [u, p] = await Promise.all([
  loadUser(1),
  fetch("/api/posts").then((r) => r.json()),
])

Roadmap