async/await is syntactic sugar built on top of Promises — it makes asynchronous code look and behave like synchronous code, improving readability and error handling.
1️⃣ The async Keyword
- Declares a function that always returns a Promise.
- Inside an
asyncfunction, you can use theawaitkeyword.
async function greet() {
return "Hello!";
}
greet().then(console.log); // Output: Hello!
2️⃣ The await Keyword
- Used inside async functions to pause execution until a Promise resolves or rejects.
- Makes code look synchronous but still runs asynchronously.
async function fetchData() {
const response = await fetch("https://jsonplaceholder.typicode.com/todos/1");
const data = await response.json();
console.log(data);
}
fetchData();
🕒 await waits for the Promise to resolve before moving to the next line.
3️⃣ Error Handling
With Promises:
fetch("api/url")
.then(res => res.json())
.catch(err => console.error(err));
With async/await (cleaner):
async function getData() {
try {
const res = await fetch("api/url");
const data = await res.json();
console.log(data);
} catch (err) {
console.error("Error:", err);
}
}
4️⃣ Key Differences
| Feature | Promises | async/await |
|---|---|---|
| Syntax | Uses .then() / .catch() chaining |
Looks like synchronous code |
| Readability | Nested or chained | Cleaner and easier to follow |
| Error Handling | .catch() |
try...catch |
| Underlying Mechanism | Built on Promises | Built on top of Promises |
💡 In Short:
async/awaitsimplifies working with Promises by making asynchronous code look synchronous and easier to read and debug, but it still uses Promises under the hood.