JavaScript Promises
A Promise is a JavaScript object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
⏳ Why Promises?
- Improve readability of async code
- Avoid "callback hell"
- Easy error handling with
.catch()
📄 Basic Syntax
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("✅ Operation successful");
} else {
reject("❌ Something went wrong");
}
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
💡 Example: Simulate API
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve("📦 Data received");
}, 2000);
});
}
fetchData()
.then(data => console.log(data))
.catch(err => console.error(err));
🔁 Chaining Promises
fetchData()
.then(data => {
console.log(data);
return "🔍 Processing data";
})
.then(processed => console.log(processed))
.catch(err => console.error(err));
📦 Promise States
- Pending: Initial state
- Fulfilled: Operation completed
- Rejected: Operation failed
💡 Tip: Promises are a foundation for modern JavaScript async tools like
fetch()
and async/await
.