What is promise?
- A Promise is an object used to handle the result of an asynchronous operation.
Example:
let promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data received successfully");
} else {
reject("Failed to receive data");
}
});
States in Promise:
A Promise has 3 states:
- Pending → Operation is still running
- Fulfilled → Operation completed successfully
- Rejected → Operation failed
Why do we need Promises?
Before Promises, asynchronous operations were commonly handled using callbacks.
example:
getUser(function(user) {
getOrders(user, function(orders) {
getPayment(orders, function(payment) {
console.log(payment);
});
});
});
When many asynchronous operations depend on each other, callbacks can become deeply nested.
This is called Callback Hell.
Promises make the code easier to organize:
getUser()
.then(user => getOrders(user))
.then(orders => getPayment(orders))
.then(payment => console.log(payment))
.catch(error => console.log(error));
So, one major reason we need Promises is:
Promises make asynchronous code easier to read, manage, and handle errors .
Uses of Promises:
- Handling asynchronous operations
- Handling success and failure
- Promise chaining
- Avoiding Callback Hell
- Working with multiple asynchronous operations
Promise to handle success:
When the operation is successful, call resolve().
const promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data received successfully");
}
});
Then we handle the successful result using .then():
promise.then(result => {
console.log(result);
});
Promise
↓
resolve()
↓
FULFILLED
↓
.then()
↓
Success result
Promise to handle error:
When the operation fails, call reject().
const promise = new Promise((resolve, reject) => {
let success = false;
if (success) {
resolve("Data received");
} else {
reject("Failed to get data");
}
});
Then handle the error using .catch():
promise.catch(error => {
console.log(error);
});
Promise
↓
reject()
↓
REJECTED
↓
.catch()
↓
Error
Handling both success and error:
Usually, we handle both together:
const promise = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Data loaded successfully");
} else {
reject("Something went wrong");
}
});
promise
.then(result => {
console.log("Success:", result);
})
.catch(error => {
console.log("Error:", error);
});

Top comments (0)