Async/Await Syntax Basics

Med

Async/await is syntactic sugar over Promises that makes asynchronous code look and behave more like synchronous code. The async keyword makes a function return a Promise, and the await keyword pauses execution until a Promise settles. This leads to cleaner, more readable code compared to Promise chains.

Interactive Visualization

Visualization coming soon

Key Points

  • async function always returns a Promise
  • await pauses execution until Promise settles
  • await can only be used inside async functions
  • Top-level await available in ES2022 (modules)
  • async/await is just Promise syntax sugar
  • Sequential by default, parallel with Promise.all()

Code Examples

Basic Async/Await

async function getUser() {
  // await pauses here until fetch completes
  const response = await fetch('/api/user');
  const user = await response.json();
  return user; // Returns a Promise!
}

// Usage
getUser().then(user => console.log(user));

// Or in another async function
async function displayUser() {
  const user = await getUser();
  console.log(user.name);
}

await pauses function execution until the Promise resolves, then returns the value.

Async Function Returns Promise

async function greet() {
  return "Hello"; // Returns Promise.resolve("Hello")
}

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

greet().then(message => console.log(message)); // "Hello"

// Even if you return a non-Promise, it's wrapped

async functions always return Promises, even if you return a plain value.

Await Multiple in Sequence

async function getDashboard() {
  // These run SEQUENTIALLY (one after another)
  const user = await fetchUser();      // Wait...
  const posts = await fetchPosts();    // Wait...
  const comments = await fetchComments(); // Wait...
  
  return { user, posts, comments };
}

// Total time = user time + posts time + comments time

Each await waits for the previous operation to complete. Sequential by default.

Top-Level Await (ES2022)

// In ES modules, await can be used at top level
// Without wrapping in async function

const response = await fetch('/api/config');
const config = await response.json();

console.log(config);

// Only works in ES modules, not regular scripts

Modern JavaScript (ES2022) allows await at the top level of modules.

Common Mistakes

  • Using await in non-async functions
  • Forgetting that async functions return Promises
  • Creating accidental sequential execution when parallel is needed
  • Not handling errors with try/catch

Interview Tips

  • Know that async/await is Promise syntax sugar
  • Understand sequential vs parallel execution
  • Know top-level await is ES2022+
  • Be able to convert between Promise chains and async/await