A Promise in JavaScript represents a value that will be available in the future.
It is used to handle asynchronous operations like API calls, timers, file reads, etc.
A Promise has 3 states:
- Pending – waiting for the result
- Fulfilled – operation completed successfully
- Rejected – operation failed
Example:
const fetchData = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Data loaded");
} else {
reject("Error loading data");
}
});
fetchData
.then(res => console.log(res))
.catch(err => console.log(err));
⭐ Difference Between Promises and async/await
Both are used for asynchronous programming, but async/await is built on top of Promises.
✅ 1. Syntax & Readability
Promises
fetchUser()
.then(data => process(data))
.then(result => console.log(result))
.catch(err => console.error(err));
❌ Can become messy → “Promise chaining”
async/await
async function loadUser() {
try {
const data = await fetchUser();
console.log(data);
} catch (err) {
console.log(err);
}
}
✔ Looks like synchronous code
✔ Cleaner and easier to understand
✅ 2. Error Handling
Promises
Errors handled using .catch()
fetchData()
.then(res => console.log(res))
.catch(err => console.log(err));
async/await
Errors handled using try...catch (more readable)
try {
const res = await fetchData();
} catch (err) {
console.log(err);
}
✅ 3. Under the Hood
- Promises work using
.then(),.catch(),.finally() - async/await is syntactic sugar on top of Promises
- Every
awaitreturns a Promise
async function test() {
return "Hello";
}
test().then(res => console.log(res)); // "Hello"
✔ async functions always return a promise
✅ 4. Async Flow Control
Promises:
Best for running tasks in parallel using:
Promise.all()
Promise.race()
Promise.allSettled()
async/await:
Best for sequential step-by-step operations.
📌 5. Which One Should You Use?
Use async/await when:
- You want cleaner code
- You have sequential operations
- You want easier error handling
Use Promises when:
- You need parallel async tasks
- You need Promise utilities (
all,race, etc.)
💡 In Short:
Promises
- Asynchronous operations
- Uses
.then()and.catch() - Good for parallel tasks
async/await
- Cleaner syntax
- Built on Promises
- Uses
try/catch - Better readability