async and await are JavaScript keywords (ES2017) that make asynchronous code look and behave like synchronous code, while still being non-blocking.
They are built on top of Promises.
✅ What is async?
- Declares a function as asynchronous
- Always returns a Promise
async function getData() {
return "Hello";
}
// Equivalent to:
Promise.resolve("Hello");
✅ What is await?
- Pauses execution inside an async function
- Waits for a Promise to resolve or reject
const data = await fetch("/api");
⚠ await can only be used inside an async function.
❓ Why Are async/await Needed?
❌ Problems with Callbacks
- Callback hell
- Hard to read
- Difficult error handling
❌ Problems with .then() chains
- Nested
.then() - Less readable for complex flows
✅ How async/await Improves Code
✔ 1. Cleaner, readable syntax
// Promise chain
fetch(url)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// async/await
try {
const res = await fetch(url);
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
✔ 2. Better error handling
- Use
try/catchinstead of.catch() - Looks like synchronous error handling
✔ 3. Easier debugging
- Stack traces are clearer
- Control flow is easier to follow
✔ 4. Sequential and Parallel Control
// Sequential
const user = await getUser();
const posts = await getPosts(user.id);
// Parallel
const [user, posts] = await Promise.all([
getUser(),
getPosts()
]);
🧠 Important Points (Interview Tips)
asyncfunctions do not block the main threadawaitpauses only that function, not the whole program- Internally uses the event loop + microtasks
awaitreturns the resolved value of a Promise
🎯 Short Interview Answer
asyncandawaitare syntactic sugar over Promises that allow writing asynchronous code in a synchronous-looking way.
They improve readability, simplify error handling using try/catch, and make async logic easier to understand and maintain, without blocking the main thread.