Async/Await

Handle asynchronous operations cleanly

#async #await #promises #asynchronous

Async/Await

Modern syntax for handling asynchronous JavaScript code.

Basic Async Function

// Async function always returns a Promise
async function fetchUser(id) {
  const response = await fetch(`/api/users/${id}`);
  const user = await response.json();
  return user;
}

// Usage
fetchUser(1)
  .then(user => console.log(user))
  .catch(err => console.error(err));

// Or with await
try {
  const user = await fetchUser(1);
  console.log(user);
} catch (err) {
  console.error(err);
}

Error Handling

async function getData() {
  try {
    const response = await fetch('/api/data');

    if (!response.ok) {
      throw new Error(`HTTP ${response.status}`);
    }

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Failed to fetch:', error);
    throw error;
  }
}

Parallel Execution

// Sequential (slow)
const user = await fetchUser(1);
const posts = await fetchPosts(1);

// Parallel (fast)
const [user, posts] = await Promise.all([
  fetchUser(1),
  fetchPosts(1)
]);

// Race
const fastest = await Promise.race([
  fetch('/api/server1'),
  fetch('/api/server2')
]);

Discover another handy tool from EditPDF.pro