A Promise in JavaScript is an object that represents the eventual completion or failure of an asynchronous operation. It allows you to handle async code more cleanly than using callbacks, avoiding “callback hell.”
1️⃣ Promise States
A Promise has three states:
- Pending – Initial state, the async operation hasn’t finished yet.
- Fulfilled – The operation completed successfully.
- Rejected – The operation failed with an error.
const promise = new Promise((resolve, reject) => {
// async task
});
2️⃣ Basic Example
const fetchData = new Promise((resolve, reject) => {
const success = true;
setTimeout(() => {
if (success) {
resolve("Data loaded successfully!");
} else {
reject("Failed to load data.");
}
}, 1000);
});
// Consuming the promise
fetchData
.then((data) => console.log(data)) // Runs on resolve
.catch((err) => console.error(err)); // Runs on reject
✅ Output after 1 second: "Data loaded successfully!"
3️⃣ Chaining Promises
You can chain multiple async operations sequentially:
fetchData
.then((data) => {
console.log(data);
return "Next step";
})
.then((msg) => console.log(msg))
.catch((err) => console.error(err));
4️⃣ Promise Utility Methods
Promise.all()– Wait for multiple promises to resolve, fails if any reject.
Promise.all([p1, p2, p3]).then(console.log).catch(console.error);
Promise.race()– Resolves or rejects as soon as one promise finishes.
Promise.race([p1, p2]).then(console.log);
Promise.allSettled()– Waits for all promises to finish, regardless of success/failure.Promise.any()– Resolves as soon as any promise fulfills; ignores rejections.
5️⃣ Async/Await Syntax (Modern)
async/await is a cleaner way to work with Promises:
async function getData() {
try {
const data = await fetchData;
console.log(data);
} catch (err) {
console.error(err);
}
}
getData();
✅ Works the same as .then().catch() but reads like synchronous code.
⚡ In short:
A Promise is a placeholder for a future result of an async operation. It can be pending, fulfilled, or rejected, and allows chaining or awaiting results to handle asynchronous code cleanly.