JavaScript Promises – Introduction
Promise in JavaScript is an object that represents the result of an asynchronous operation (something that takes time, like fetching data).
A Promise can be in 3 states:
Pending – operation is still running
Fulfilled – operation completed successfully
Rejected – operation failed
Why Promises?**
Before promises, JavaScript used callbacks, which caused callback hell (messy nested code).
Promises make async code clean, readable, and manageable.
Creating a Promise
const myPromise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Task completed");
} else {
reject("Task failed");
}
});
Consuming a Promise
myPromise
.then((result) => {
console.log(result); // Task completed
})
.catch((error) => {
console.log(error); // Task failed
});
Promise Example (Real-life style)
function orderFood() {
return new Promise((resolve, reject) => {
let foodReady = true;
if (foodReady) {
resolve("Food delivered 🍔");
} else {
reject("Order cancelled ❌");
}
});
}
orderFood()
.then(msg => console.log(msg))
.catch(err => console.log(err));
Promise Methods
.then() → runs when promise is fulfilled
.catch() → runs when promise is rejected
.finally()
→ runs always
myPromise.finally(() => {
console.log("Process finished");
});
Simple Summary**
Promise handles asynchronous operations
Makes code cleaner than callbacks
Used heavily with fetch, APIs, async/await
Top comments (0)