In JavaScript, a Promise is an object that represents the result of an asynchronous operation—something that may finish now, later, or fail.
🔹 Simple Meaning
A Promise is like a guarantee:
“I will give you a result later — either success or failure.”
🔹 Why Promises are Used
JavaScript often runs tasks like:
Fetching data from a server 🌐
Reading files 📂
Waiting for a timer ⏱️
These take time, so Promises help handle them without blocking the program.
🔹 States of a Promise
A Promise has 3 states:
Pending → initial state (waiting)
Fulfilled → operation successful
Rejected → operation failed
🔹 Basic Syntax
JavaScript
let promise = new Promise(function(resolve, reject) {
let success = true;
if(success) {
resolve("Task completed!");
} else {
reject("Task failed!");
}
});
🔹 Using a Promise
JavaScript
promise
.then(function(result) {
console.log(result); // if success
})
.catch(function(error) {
console.log(error); // if error
});
🔹 Real Example
JavaScript
function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received");
}, 2000);
});
}
getData().then(data => console.log(data));
👉 Output after 2 seconds:
Data received
🔹 Promise Methods
.then() → runs when successful
.catch() → runs when error occurs
.finally() → runs always