What is async/await?

async/await is a modern JavaScript feature (ES2017) that provides a cleaner way to work with promises. Instead of chaining .then() calls, you can write asynchronous code that reads like synchronous code.

The Basics

async functions always return a promise:

async function myFunction() {
  return "Hello";
}

// Equivalent to:
function myFunction() {
  return Promise.resolve("Hello");
}

await pauses execution until a promise resolves:

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

Comparing Promises vs Async/Await

With Promises:

function getUser() {
  return fetch('/api/user')
    .then(response => response.json())
    .then(user => {
      return fetch(`/api/posts/${user.id}`);
    })
    .then(response => response.json())
    .then(posts => {
      console.log(posts);
      return posts;
    })
    .catch(error => console.error(error));
}

With Async/Await:

async function getUser() {
  try {
    const response = await fetch('/api/user');
    const user = await response.json();

    const postsResponse = await fetch(`/api/posts/${user.id}`);
    const posts = await postsResponse.json();

    console.log(posts);
    return posts;
  } catch (error) {
    console.error(error);
  }
}

Error Handling

Use try/catch blocks for error handling, which is more intuitive than .catch():

async function riskyOperation() {
  try {
    const result = await mightFail();
    return result;
  } catch (error) {
    // Handle specific errors
    if (error.code === 'NETWORK_ERROR') {
      console.error('Network failed');
    }
    throw error; // Re-throw if needed
  }
}

Important Rules

  1. await only works inside async functions (or top-level in modules)
  2. await pauses execution of that function, but doesn't block the entire program