Async / Await
Promises improved asynchronous JavaScript a lot,
but real-world code can still feel hard to read
when many .then() calls are chained together.
Async and await were introduced to make asynchronous code look and behave more like normal, synchronous code.
Why Async / Await?
Async/await helps developers:
- Write cleaner asynchronous code
- Avoid deeply nested promise chains
- Understand execution flow more easily
Under the hood, async/await still uses promises. It just provides a better syntax.
The async Keyword
The async keyword is used before a function
to indicate that it returns a promise.
async function greet() {
return "Hello World";
}
Even though this looks like a normal return, JavaScript automatically wraps the value in a promise.
The await Keyword
The await keyword pauses the execution of an
async function until a promise is resolved.
async function showData() {
let result = await fetchData();
console.log(result);
}
This makes asynchronous code easier to read and reason about.
Simple Comparison
Promise-based approach:
fetchData()
.then(function (data) {
console.log(data);
})
.catch(function (error) {
console.log(error);
});
Async/await approach:
async function loadData() {
try {
let data = await fetchData();
console.log(data);
} catch (error) {
console.log(error);
}
}
The second version is more readable and structured.
Error Handling with try...catch
Async/await uses standard try...catch
blocks for error handling.
async function processData() {
try {
let response = await fetchData();
console.log(response);
} catch (error) {
console.log("Error occurred");
}
}
This keeps error handling clean and centralized.
Important Rules to Remember
awaitworks only insideasyncfunctions- An
asyncfunction always returns a promise - Execution pauses only inside the async function
Real-World Example
Fetching data and updating the UI:
async function loadUser() {
let user = await fetchUser();
document.getElementById("name").innerText = user.name;
}
This pattern is widely used in modern applications.
Common Beginner Mistakes
- Using
awaitoutside anasyncfunction - Forgetting error handling
- Thinking async code becomes synchronous
Async/await improves readability, not execution speed.
Thumb Rules
- Use async/await for readable async code
- Always handle errors
- Remember promises are still involved
- Prefer clarity over clever shortcuts
What Comes Next?
Now that asynchronous code is easier to manage, the next step is organizing code into reusable pieces.
In the next lesson, we will learn about JavaScript modules.