DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

⏳ Async/Await Explained Like You're 5

Wait for the coffee, then continue

Day 53 of 149

👉 Full deep-dive with code examples


The Coffee Shop

With Promises:

  • "I'll order coffee"
  • .then(() => wait for coffee)
  • .then(() => sit down)
  • .then(() => drink)

With Async/Await:

  • Order coffee
  • Wait for it
  • Sit down
  • Drink

Reads like normal steps! ☕


The Syntax

Before (Promises):

fetchUser()
  .then((user) => fetchPosts(user.id))
  .then((posts) => displayPosts(posts))
  .catch((err) => console.error(err));
Enter fullscreen mode Exit fullscreen mode

After (Async/Await):

async function loadDashboard() {
  const user = await fetchUser();
  const posts = await fetchPosts(user.id);
  displayPosts(posts);
}
Enter fullscreen mode Exit fullscreen mode

Looks like regular code!


The Rules

  1. async before a function = the function returns a Promise
  2. await before a Promise (or “thenable”) = "Pause this async function until it settles, then continue"
  3. await usually works inside async functions (and in some environments, at the top level)

Note: await makes code easier to read, but it doesn't automatically run work in parallel — it just waits at that line. Use patterns like Promise.all() when tasks are independent.


Error Handling

async function loadData() {
  try {
    const data = await fetchData();
    return data;
  } catch (error) {
    console.error("Failed!", error);
  }
}
Enter fullscreen mode Exit fullscreen mode

Use try/catch just like regular code!


In One Sentence

Async/await makes asynchronous code easier to read by letting you write Promise-based logic in a step-by-step style.


🔗 Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)