Promise is a JavaScript object that represents the eventual completion or failure of an asynchronous operation.
It has three states:
- Pending – initial state
- Fulfilled – operation succeeded
- Rejected – operation failed
🧪 Promise Example
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data loaded");
}, 1000);
});
promise.then(console.log).catch(console.error);
🔹 Why Promises Were Introduced
Before Promises, async code used callbacks, which caused:
- Callback hell (nested callbacks)
- Poor readability
- Difficult error handling
Promises provide: ✔ Cleaner chaining
✔ Centralized error handling
✔ Better async control
🔹 What Is async / await?
async and await are syntax built on top of Promises to make async code look synchronous and readable.
async→ makes a function return a Promiseawait→ pauses execution until the Promise resolves
🧪 Example Using async/await
async function fetchData() {
const response = await fetch("/api/data");
const data = await response.json();
console.log(data);
}
🔄 Promise vs async/await
❌ Promise chaining
fetch("/api/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(console.error);
✅ async/await
async function getData() {
try {
const res = await fetch("/api/data");
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}
🔥 Why We Use async and await
✔ Improves readability
✔ Avoids nested .then()
✔ Easier error handling (try/catch)
✔ Looks like synchronous code
✔ Easier debugging
🎯 Short Interview Answer
A Promise represents the result of an asynchronous operation that may succeed or fail in the future.
asyncandawaitare used to write Promise-based code in a more readable and synchronous-looking way, making async logic easier to understand and maintain.
⭐ One-line summary
Promises handle async results; async/await makes them readable and manageable.