async and await are keywords in JavaScript used to handle asynchronous operations in a cleaner, more readable way than traditional promises or callbacks.
🔹 async Function:
- Declares a function as asynchronous.
- Always returns a Promise.
- Allows the use of
awaitinside it.
async function getData() {
return "Hello";
}
🔹 await Keyword:
- Can only be used inside an async function.
- Pauses the execution of the function until the Promise is resolved.
- Makes asynchronous code look like synchronous code.
async function fetchData() {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log(data);
}
✅ Comparison with Promises:
Using .then():
fetch(url)
.then(res => res.json())
.then(data => console.log(data));
Using async/await:
async function getData() {
const res = await fetch(url);
const data = await res.json();
console.log(data);
}
✅ Error Handling:
Use try...catch with async/await for cleaner error handling.
async function getUser() {
try {
const res = await fetch("invalid-url");
const data = await res.json();
console.log(data);
} catch (error) {
console.error("Error:", error);
}
}
📝 In Summary:
asyncdeclares a function that returns a Promise.awaitwaits for a Promise to resolve before continuing.- Together, they make asynchronous code easier to write and read, avoiding nested
.then()chains.