Mastering Async/Await in JavaScript
Contents
- What is async/await?
- Basic Example
- Why It Matters
- Error Handling
- Parallel vs Sequential
- Async in Loops
- Conclusion
Asynchronous programming is at the heart of modern JavaScript — from making API calls to handling events in the browser. One of the most powerful tools for handling async operations is async/await.
What is async/await?
async
and await
are syntactic sugar built on top of Promises, introduced in ES2017. They make asynchronous code look and behave like synchronous code, improving readability and maintainability.
Basic Example
async function fetchUser() { const response = await fetch('https://api.example.com/user'); const user = await response.json(); console.log(user); }
Without await
, you’d need to chain Promises with .then()
, making code harder to follow.
Why It Matters
- Readability: Async/await code looks like standard synchronous flow.
- Debugging: Easier to step through with breakpoints.
- Error handling: Cleaner with try/catch blocks.
Error Handling
async function fetchData() { try { const res = await fetch('https://api.example.com/data'); const json = await res.json(); console.log(json); } catch (err) { console.error('Something went wrong:', err); } }
Parallel vs Sequential
One common mistake is awaiting async calls sequentially when they can run in parallel.
// Sequential (slower) const user = await fetchUser(); const posts = await fetchPosts(user.id); // Parallel (faster) const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]);
Async in Loops
Using await
inside loops can be tricky. Use for...of
instead of forEach
.
// ❌ This won't wait properly [1,2,3].forEach(async n => { await delay(n * 1000); console.log(n); }); // ✅ This works for (const n of [1,2,3]) { await delay(n * 1000); console.log(n); }
Conclusion
Mastering async/await means cleaner code, fewer bugs, and easier maintenance. While Promises are the foundation, async/await is what makes writing asynchronous code feel natural in JavaScript.
Leave a Reply
Want to join the discussion?Feel free to contribute!