#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 6 of 50medium

What is async/await in JavaScript?

Understanding async/await syntax for Promises.

What You'll Learn

  • async/await syntax
  • Error handling
  • Best practices

What is async/await?

async/await is syntactic sugar over Promises that makes asynchronous code look synchronous.

Basic Syntax

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

Key Points

  • async functions always return a Promise
  • await pauses execution until Promise resolves
  • Use try/catch for error handling

Parallel Execution

code.jsJavaScript
// Sequential (slower)
const a = await fetchA();
const b = await fetchB();

// Parallel (faster)
const [a, b] = await Promise.all([fetchA(), fetchB()]);

Arrow Function Syntax

code.jsJavaScript
const fetchUser = async (id) => {
  const response = await fetch(`/users/${id}`);
  return response.json();
};