Curriculum / Advanced / Lesson 22

Async/Await

Writing asynchronous code that looks synchronous.

22 of 30
advanced 📖 6 min read 🎯 4 questions

What is Async/Await?

Async/await is syntactic sugar on top of Promises that makes asynchronous code look and behave more like synchronous code. It's built on Promises and works with any function that returns a Promise.

💡 Key insight async functions always return a Promise. await pauses the function execution until the Promise resolves.

Async Functions

// This function returns a Promise
async function fetchData() {
  return "Data fetched!";
}

fetchData().then(result => console.log(result));

The await Keyword

await can only be used inside async functions. It pauses execution until the Promise resolves.

async function getData() {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  return data;
}

Error Handling with try/catch

async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Failed to fetch:', error);
  }
}

Parallel Execution

Use Promise.all() with await for parallel operations.

async function getMultipleData() {
  const [data1, data2] = await Promise.all([
    fetch('/api/1').then(r => r.json()),
    fetch('/api/2').then(r => r.json())
  ]);
  console.log(data1, data2);
}

Common Mistakes

Quick Quiz

1. What does the async keyword do?

2. Can await be used outside an async function?

3. How do you handle errors in async/await?

4. What does an async function return?

Summary

Back to curriculum