Async/Await

Async/await is a modern JavaScript syntax for handling asynchronous operations, built on top of Promises. It makes asynchronous code look and behave more like synchronous code, improving readability and maintainability.

Syntax

javascript
// Async function declaration
async function fetchUserData(userId) {
  const response = await fetch(`/api/users/${userId}`)
  const data = await response.json()
  return data
}

// Async arrow function
const fetchUserData = async (userId) => {
  const response = await fetch(`/api/users/${userId}`)
  const data = await response.json()
  return data
}

Key Features

async Keyword The async keyword before a function declaration makes the function return a Promise. Even if you return a plain value, it will be wrapped in a resolved Promise.

await Keyword The await keyword can only be used inside async functions. It pauses the execution of the function until the Promise is resolved or rejected.

Error Handling

javascript
async function loadData() {
  try {
    const response = await fetch('/api/data')
    if (!response.ok) {
      throw new Error('Failed to fetch data')
    }
    const data = await response.json()
    return data
  } catch (error) {
    console.error('Error loading data:', error)
    throw error
  }
}

Multiple Concurrent Requests

javascript
// Sequential (slower)
const user = await fetchUser(userId)
const posts = await fetchPosts(userId)

// Concurrent (faster)
const [user, posts] = await Promise.all([
  fetchUser(userId),
  fetchPosts(userId)
])

Benefits

  • Cleaner, more readable code compared to Promise chains
  • Easier error handling with try/catch
  • Better debugging experience
  • Familiar control flow for developers

Learn More