A Promise in JavaScript is an object that represents the eventual completion or failure of an asynchronous operation.
It helps handle async code (like API calls, file reads, or timers) in a cleaner and more readable way than traditional callbacks.
1️⃣ Promise States
A Promise can be in one of three states:
- Pending → Initial state (waiting for result)
- Fulfilled → Operation completed successfully (
.then()runs) - Rejected → Operation failed (
.catch()runs)
2️⃣ Creating a Promise
You can create a Promise using the Promise constructor:
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) resolve("Data fetched successfully!");
else reject("Error fetching data!");
});
3️⃣ Consuming a Promise
Use .then() and .catch() to handle results:
myPromise
.then(result => console.log(result)) // Runs if resolved
.catch(error => console.error(error)) // Runs if rejected
.finally(() => console.log("Done!")); // Runs in both cases
Output:
Data fetched successfully!
Done!
4️⃣ Promises with Async/Await (Cleaner Syntax)
Instead of chaining .then() and .catch(), use async/await:
async function fetchData() {
try {
const result = await myPromise;
console.log(result);
} catch (error) {
console.error(error);
}
}
fetchData();
5️⃣ Promise Chaining
You can chain multiple async operations:
fetch("https://api.example.com/data")
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error("Error:", err));
💡 In Short:
A Promise is a placeholder for a value that will be available in the future —
It simplifies asynchronous code, replacing callback hell with a cleaner, structured approach.