Async/Await - Modern Promise Syntax

Intermediate
120 XP
50 min
Lesson Content

Async/Await - Modern Promise Syntax

Async/await is syntactic sugar for promises, making asynchronous code look and behave more like synchronous code. It's easier to read and write.

Async Functions

// Function marked with 'async' always returns a Promise
async function fetchData() {
  return 'Data';
}

// Arrow function
const fetchData = async () => {
  return 'Data';
};

Await Keyword

async function getData() {
  // await pauses execution until promise resolves
  const data = await fetch('/api/data');
  const json = await data.json();
  return json;
}

Error Handling

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

Multiple Async Operations

// Sequential (one after another)
async function sequential() {
  const first = await fetch('/api/first');
  const second = await fetch('/api/second');
  return { first, second };
}

// Parallel (at the same time)
async function parallel() {
  const [first, second] = await Promise.all([
    fetch('/api/first'),
    fetch('/api/second')
  ]);
  return { first, second };
}

Benefits of Async/Await

  • Cleaner, more readable code
  • Easier error handling with try-catch
  • Better debugging experience
  • Works with existing promise-based APIs
Example Code

Use async/await to handle asynchronous operations

// Simulate async operations
function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function fetchUser(id) {
  await delay(500); // Simulate network delay
  return { id, name: `User ${id}`, email: `user${id}@example.com` };
}

async function fetchUserPosts(userId) {
  await delay(300);
  return [
    { id: 1, title: 'Post 1', userId },
    { id: 2, title: 'Post 2', userId }
  ];
}

// Using async/await
async function getUserData(userId) {
  try {
    console.log('Fetching user...');
    const user = await fetchUser(userId);
    console.log('User:', user);
    
    console.log('Fetching posts...');
    const posts = await fetchUserPosts(userId);
    console.log('Posts:', posts);
    
    return { user, posts };
  } catch (error) {
    console.error('Error:', error);
    throw error;
  }
}

// Call the async function
getUserData(1)
  .then(data => console.log('Complete data:', data))
  .catch(error => console.error('Failed:', error));

Expected Output:

Fetching user...
User: {id:1,name:User 1,email:user1@example.com}
Fetching posts...
Posts: [{id:1,title:Post 1,userId:1},{id:2,title:Post 2,userId:1}]
Complete data: {user:{id:1,name:User 1,email:user1@example.com},posts:[{id:1,title:Post 1,userId:1},{id:2,title:Post 2,userId:1}]}
Study Tips
  • Read the theory content thoroughly before practicing
  • Review the example code to understand key concepts
  • Proceed to the Practice tab when you're ready to code