Async Functions and Await: Modern Asynchronous JavaScript
While Promises (with .then(), .catch(), .finally()) improve on callback hell, ES2017 introduced async functions and the await keyword to make asynchronous code look synchronous and far more readable.
1. Understanding async Functions
An async function always returns a Promise. Inside it you can use await to pause execution until another Promise settles.
Basic Async Function
Loading Code Editor...
2. The await Keyword
You can only use await inside an async function. It pauses until the awaited Promise settles, throwing an error if the Promise rejects.
Using Await
Loading Code Editor...
3. Error Handling with try...catch
async/await lets you use normal try...catch around multiple awaits, which is far cleaner than chaining .catch() on each Promise.
Async/Await Error Handling
Loading Code Editor...
4. Chaining Promises vs. async/await
| Feature | Promise Chaining | async/await |
|---|---|---|
| Readability | .then().then() can grow verbose | Looks like regular synchronous code |
| Error Handling | .catch() at end or per chain | Use try...catch |
| Flow Control | Explicitly returns Promises | Execution pauses at each await |
Exercise: Refactor Fetch Chain to async/await
Instructions: Refactor the original fetch-and-comments Promise chain into a single async function using await, with proper try...catch and status checks.
Refactor to Async/Await Exercise
Loading Code Editor...

