Async/Await: The Modern Standard

Async/Await: The Modern Standard in JavaScript: Even with Promises, the code can look weird with all the and blocks.

Concept Explanation

Even with Promises, the code can look weird with all the .then() and .catch() blocks. Async/Await is a newer way to write the exact same logic, but it looks like standard, synchronous code. It makes async programming finally feel "Natural."


Syntax or Core Structure

The Two Keywords

  1. async: Must be placed before the function. It tells JS this function automatically returns a Promise.
  2. await: Can only be used inside an async function. It literally tells the code: "Pause here until the promise is done."
async function getUserData() {
    try {
        const response = await fetch("https://api.example.com/user");
        const user = await response.json();
        console.log(user.name);
    } catch (error) {
        console.log("Error happened!", error);
    }
}

Common Mistakes

  1. Forgetting 'async': You cannot use await inside a regular function. It will throw a syntax error.
  2. The Serial Trap: Awaiting things one-by-one is slow.
  • const a = await getA(); const b = await getB(); (Slow! Total time = A + B)
  • const [a, b] = await Promise.all([getA(), getB()]); (Fast! Total time = whichever is slower)
  1. Try/Catch Neglect: In async/await, you MUST wrap your code in try/catch or your app will crash silently on errors.

Best Practices

  • Clean Syntax: Use async/await for almost everything. It's the industry standard in 2026.
  • Parallelize when possible: Don't await independent tasks sequentially.
  • Top-Level Await: In modern ES Modules, you can use await at the top of your file without a function wrapper!

Practice Exercises

  1. The Refactor: Take your Promise chain from the previous exercise and rewrite it using async/await. Compare the readability.
  2. The Error Tester: Write an async function that deliberately tries to fetch a broken URL and use try/catch to print a custom error message.
  3. The Loopers: Use for...of with await to print "Second 1", "Second 2", "Second 3" with a 1-second delay between each.