Promises in JavaScript – Then, Catch and Finally
A Promise handles an operation that finishes later. Use then() for success, catch() for errors, and finally() for cleanup. These methods help keep asynchronous code clear and organised.
1. Why Do We Need Promises?
Imagine a customer places an order on an online shopping website. Payment confirmation may take a few seconds. Should the page freeze while waiting?
JavaScript can continue running other work. It handles the payment result when the operation finishes.
Without a Promise, we might use callbacks and manage success and failure separately. This can become difficult as more operations are added.
2. What Is a Promise?
A Promise = an object that represents a future result.
A Promise has three states:
- Pending: The operation is still running.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
Once fulfilled or rejected, the Promise is settled. It cannot change to another state.
3. Understand Then, Catch and Finally
then() – Handle Success
then() runs when the Promise is fulfilled. It receives the successful result.
catch() – Handle Errors
catch() runs when the Promise is rejected. It receives the rejection reason.
finally() – Run Cleanup
finally() runs after success or failure. It does not receive the result as an argument.
4. Follow a Payment Confirmation
Here is the flow for an online order payment. The success and failure paths lead to cleanup.
The payment Promise starts pending, then follows its success or failure path before cleanup.
5. Create a Promise in JavaScript
Use the Promise constructor when you need to create a Promise. Its executor receives resolve and reject.
The following example simulates an order payment. The timer represents a delayed response.
const paymentPromise = new Promise((resolve, reject) => {
setTimeout(() => {
const paymentSuccessful = true;
if (paymentSuccessful) {
resolve("Payment completed successfully");
} else {
reject("Payment could not be completed");
}
}, 1000);
});
paymentPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.error(error);
})
.finally(() => {
console.log("Payment process finished");
});
Payment completed successfully Payment process finished
6. Handle a Failed Promise
Now change paymentSuccessful to false. The Promise becomes rejected.
const paymentPromise = Promise.reject(
"Payment was declined"
);
paymentPromise
.then((result) => {
console.log(result);
})
.catch((error) => {
console.log("Error:", error);
})
.finally(() => {
console.log("Loading indicator hidden");
});
Error: Payment was declined Loading indicator hidden
7. How Promise Chaining Works
Each then() returns a new Promise. This lets us connect multiple steps.
Promise.resolve("Payment confirmed")
.then>((message) => {
console.log(message);
return "Order prepared";
})
.then>((message) => {
console.log(message);
})
.catch((error) => {
console.error(error);
})
.finally(() => {
console.log("Order process completed");
});
Payment confirmed Order prepared Order process completed
Returning a value passes it to the next then(). Returning another Promise makes the chain wait for it.
8. Then vs Catch vs Finally
| Method | When it runs | Main purpose |
|---|---|---|
then() |
On fulfillment | Process the successful result |
catch() |
On rejection | Handle the error |
finally() |
After settlement | Perform cleanup |
9. Common Mistakes
- Forgetting to return: Return values when the next step needs them.
- Ignoring errors: Add a
catch()handler to handle rejections. - Using finally for results: Use
then()orcatch()to read the outcome.
Important: finally() normally passes through the previous result or rejection. But if its callback throws an error or returns a rejected Promise, the chain becomes rejected.
10. Quick Practice
- Create a Promise that resolves with an order number after one second.
- Create a rejected Promise and handle its error with
catch(). - Use
finally()to print a cleanup message in both cases.
11. Interview Quick Check
What is a Promise in JavaScript?
A Promise represents a result that may become available later. It can be pending, fulfilled or rejected.
What is the difference between then(), catch() and finally()?
then() handles success, while catch() handles rejection. finally() runs cleanup after either outcome.
Does finally() receive the Promise result?
No. Its callback does not receive the fulfillment value or rejection reason. The Promise chain normally keeps the previous outcome.
12. Next Step
Promises make asynchronous JavaScript easier to organise. Next, explore Async and Await in JavaScript to write Promise-based code in a simpler style.
Keep practising with real examples and build your understanding one step at a time.