Hiprup

What is async/await and how does it work?

async/await is syntax built on Promises that lets asynchronous code read like synchronous code.

  • async — marks a function that always returns a Promise.

  • await — pauses inside an async function until a Promise settles, then returns its value.

  • Error handling — wrap awaited calls in try/catch instead of using .catch().

Performance tip: awaiting calls one by one runs them in sequence. To run independent tasks together, start them first and await Promise.all.

// Basic async/await
async function getUser(id) {
  const response = await fetch(`/api/users/${id}`);
  if (!response.ok) throw new Error(`HTTP ${response.status}`);
  return response.json(); // Returns a Promise
}

// Error handling with try/catch
async function loadDashboard(userId) {
  try {
    const user = await getUser(userId);
    const orders = await getOrders(user.id);
    return { user, orders };
  } catch (err) {
    console.error('Dashboard load failed:', err.message);
    throw err;
  }
}

// Parallel with async/await
async function loadAll(userId) {
  // Sequential (slow)
  const user = await getUser(userId);     // Wait 1s
  const posts = await getPosts(userId);    // Wait 1s (total: 2s)

  // Parallel (fast)
  const [user2, posts2] = await Promise.all([
    getUser(userId),    // Both start immediately
    getPosts(userId)    // Total: 1s (max of both)
  ]);
}

// Async in loops
async function processItems(items) {
  // Sequential processing
  for (const item of items) {
    await processItem(item); // One at a time
  }

  // Parallel processing
  await Promise.all(items.map(item => processItem(item)));
}

// Top-level await (ES modules)
const data = await fetch('/api/config').then(r => r.json());

async marks the function, await pauses until the Promise resolves. try/catch handles rejections. The parallel example shows the common mistake: sequential awaits are slow, Promise.all is fast.

Loop processing: for...of with await is sequential, Promise.all(map) is parallel. Choose based on whether items can be processed independently.

Show sequential vs parallel (await in sequence vs Promise.all). The for...of loop (sequential) vs map+Promise.all (parallel) is frequently asked. try/catch replaces .catch for error handling.

Know that async always returns a Promise.

What is async/await and how does it work? | Hiprup