Async / Await is a modern JavaScript feature that makes working with asynchronous code simpler, cleaner, and more readable. It is built on top of Promises and helps you write asynchronous logic that looks and behaves like synchronous code.
Before async/await, developers relied heavily on callbacks and Promise chains, which could become hard to read and maintain. Async/await solves this problem.
The async keyword is used to declare a function that always returns a Promise.
async function greet() {
return "Hello World";
}
greet().then(message => console.log(message));
The await keyword is used inside an async function to pause execution until a Promise is resolved.
async function fetchData() {
let response = await fetch("https://api.example.com/data");
let data = await response.json();
console.log(data);
}
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error));
async function getData() {
try {
const res = await fetch(url);
const data = await res.json();
console.log(data);
} catch (error) {
console.log(error);
}
}
async function loadUser() {
try {
const response = await fetch("/user");
const user = await response.json();
console.log(user);
} catch (error) {
console.error("Error loading user:", error);
}
}
| Feature | Promises | Async / Await |
|---|---|---|
| Syntax | .then() chaining | Looks synchronous |
| Readability | Medium | High |
| Error Handling | .catch() | try...catch |
| Modern Usage | Supported | Preferred |