In JavaScript, a Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
Think of it like a “placeholder” for a value that will be available in the future (like a pending online order—you don’t have it now, but you’ll get it later, or it might fail).
States of a Promise
A Promise can be in one of three states:
- Pending → Initial state, neither fulfilled nor rejected.
- Fulfilled → Operation completed successfully, and the promise has a result.
- Rejected → Operation failed, and the promise has a reason (error).
Syntax
let promise = new Promise((resolve, reject) => {
// async operation
let success = true;
if (success) {
resolve("Task completed successfully!");
} else {
reject("Something went wrong.");
}
});
Consuming a Promise
You handle the result with .then(), .catch(), and .finally():
promise
.then(result => {
console.log(result); // if resolved
})
.catch(error => {
console.log(error); // if rejected
})
.finally(() => {
console.log("Promise finished (success or failure).");
});
✅ Key Points about Promises:
- They simplify handling of asynchronous tasks (like API calls, file reading, setTimeout).
- They help avoid callback hell (deeply nested callbacks).
- They are chainable (
.then().then().catch()). - Often used with
async/awaitfor cleaner code.
