Async/Await

Modern Asynchronous JavaScript

Async/await is modern syntax that makes asynchronous code look and behave more like synchronous code, improving readability.

The 'async' keyword makes a function return a Promise, while 'await' pauses function execution until a Promise is resolved.

This approach eliminates promise chaining and makes error handling with try/catch more natural and familiar.

// Traditional Promise syntax
function fetchData() {
  return fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => {
      console.log(data);
      return data;
    })
    .catch(error => {
      console.error('Error:', error);
    });
}

// Modern async/await syntax
async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}

// Async function always returns a Promise
async function greet(name) {
  return `Hello, ${name}!`;
}

greet('Alice').then(message => console.log(message));

// Multiple async operations in parallel
async function fetchMultiple() {
  try {
    const [users, posts, comments] = await Promise.all([
      fetch('/api/users').then(r => r.json()),
      fetch('/api/posts').then(r => r.json()),
      fetch('/api/comments').then(r => r.json())
    ]);

    return { users, posts, comments };
  } catch (error) {
    console.error('Error fetching data:', error);
  }
}
  • async keyword - Declares an async function that returns a Promise
  • await keyword - Pauses execution until Promise resolves
  • try/catch - Handle errors in async functions naturally
  • Sequential operations - Multiple awaits run one after another
  • Parallel operations - Use Promise.all() with await for concurrent execution
  • Return values - Async functions automatically wrap returns in Promise
  • Top-level await - Can use await at module level in modern JS

Try Async/Await

<div class="async-demo">
  <h3>Async/Await Examples</h3>

  <div class="example">
    <h4>1. Sequential Operations</h4>
    <button id="sequentialBtn">Run Sequential</button>
    <div id="sequentialOutput"></div>
  </div>

  <div class="example">
    <h4>2. Parallel Operations</h4>
    <button id="parallelBtn">Run Parallel</button>
    <div id="parallelOutput"></div>
  </div>

  <div class="example">
    <h4>3. Error Handling</h4>
    <button id="successAsyncBtn">Success</button>
    <button id="errorAsyncBtn">Error</button>
    <div id="errorOutput"></div>
  </div>
</div>

Note: await only in async: The await keyword can only be used inside async functions (or at top level in modules).

Note: Error Handling: Use try/catch blocks to handle errors from awaited promises. Uncaught errors will reject the async function.

Note: Performance: Use Promise.all() with await when operations can run in parallel - it's much faster than sequential awaits.