JSTAcademy
0 XP
Dashboard
Crash Courses
Async JavaScript — Promises & async/await
13 min
Masters+175 XP
Crash Courses · Masters

Async JavaScript — Promises & async/await

Write async code that fetches data, handles errors, and runs operations in parallel.
13 min read+175 XP on completionCert: JavaScript Crash Course
Tap any word in the text below to start reading from there.

Async JavaScript Promises & async/await

Every real web app fetches data, calls APIs, reads from databases. JavaScript handles all of this asynchronously without blocking the page.

Promises

const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve('data'), 1000)
})

p.then(data => console.log(data))
 .catch(err => console.error(err))
 .finally(() => setLoading(false))

async/await

async function loadUserPosts(userId) {
  try {
    const res = await fetch(`/api/user/${userId}`)
    if (!res.ok) throw new Error(`HTTP ${res.status}`)
    const user = await res.json()

    const postsRes = await fetch(`/api/posts/${user.id}`)
    return await postsRes.json()
  } catch (err) {
    console.error('Failed:', err)
    throw err
  }
}

Rules: await only inside async functions. async functions always return a Promise. Rejected awaited Promises jump to catch.

Sequential vs Parallel

// Sequential — total = A + B + C
const user = await getUser(id)
const posts = await getPosts(id)
const followers = await getFollowers(id)

// Parallel — total = max(A, B, C)
const [user, posts, followers] = await Promise.all([
  getUser(id), getPosts(id), getFollowers(id),
])

Promise.allSettled

const results = await Promise.allSettled([
  fetch(url1), fetch(url2), fetch(url3)
])

results.forEach(r => {
  if (r.status === 'fulfilled') process(r.value)
  else logError(r.reason)
})

The fetch Pattern

async function api(path, options = {}) {
  const res = await fetch(`/api${path}`, {
    headers: { 'Content-Type': 'application/json', ...options.headers },
    ...options,
  })
  if (!res.ok) {
    const body = await res.json().catch(() => ({}))
    throw new Error(body.message ?? `HTTP ${res.status}`)
  }
  return res.json()
}

fetch only rejects on network failure. A 404 is still a resolved Promise always check res.ok.

0%