Async/Await in JavaScript

Understanding asynchronous JavaScript with async/await syntax

Async/Await in JavaScript

Async/await makes asynchronous code look and behave more like synchronous code.

Basic Usage

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

Error Handling

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}

Multiple Awaits

async function fetchMultiple() {
  const [users, posts] = await Promise.all([
    fetch('/api/users').then(r => r.json()),
    fetch('/api/posts').then(r => r.json())
  ]);
  return { users, posts };
}