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
- async: Must be placed before the function. It tells JS this function automatically returns a Promise.
- 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
- Forgetting 'async': You cannot use
awaitinside a regular function. It will throw a syntax error. - 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)
- Try/Catch Neglect: In async/await, you MUST wrap your code in
try/catchor 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
awaitat the top of your file without a function wrapper!
Practice Exercises
- The Refactor: Take your Promise chain from the previous exercise and rewrite it using
async/await. Compare the readability. - The Error Tester: Write an async function that deliberately tries to fetch a broken URL and use
try/catchto print a custom error message. - The Loopers: Use
for...ofwithawaitto print "Second 1", "Second 2", "Second 3" with a 1-second delay between each.