Promises in Node.js
A Promise in JavaScript represents the eventual completion or failure of an asynchronous operation and its resulting value. Promises help us organize asynchronous code.
1. What is a Promise?
Imagine Samadhan asks Pradnya to prepare a course report at CIIT Training Institute. Pradnya may still be preparing it, may complete it successfully, or may fail to prepare it. A Promise represents this pending work and its eventual result.
2. States of a Promise
| State | Meaning | Example |
|---|---|---|
| Pending | The operation has not completed yet. | Pradnya is preparing the report. |
| Fulfilled | The operation completed successfully. | The report is ready. |
| Rejected | The operation failed. | The report could not be prepared. |
A Promise starts in the pending state and settles as fulfilled or rejected. Once settled, its state does not change again.
3. Creating a Promise
We create a Promise using the new Promise() constructor.
It receives an executor function with two important parameters:
resolve and reject.
const coursePromise = new Promise((resolve, reject) => {
let courseReady = true;
if (courseReady) {
resolve("Course details are ready!");
} else {
reject("Course details are not available.");
}
});
coursePromise
.then((message) => {
console.log(message);
})
.catch((error) => {
console.log(error);
});
Output
Course details are ready!
Explanation
new Promise()creates a Promise.resolve()fulfills the Promise with a value.reject()rejects the Promise with a reason..then()handles fulfillment..catch()handles rejection.
4. Using then()
The then() method is used to handle a fulfilled Promise.
Let's see an example with Samadhan and CIIT Training Institute.
const admissionPromise = new Promise((resolve) => {
resolve("Samadhan's admission is confirmed at CIIT Training Institute.");
});
admissionPromise.then((message) => {
console.log(message);
});
Output
Samadhan's admission is confirmed at CIIT Training Institute.
When the Promise is fulfilled, the callback passed to
then() receives the resolved value.
5. Using catch()
The catch() method handles a rejected Promise.
const resultPromise = new Promise((resolve, reject) => {
reject("Course registration failed.");
});
resultPromise
.then((message) => {
console.log(message);
})
.catch((error) => {
console.log("Error: " + error);
});
Output
Error: Course registration failed.
Because the Promise is rejected, the error handler in
catch() runs instead of the fulfillment handler.
6. Using finally()
The finally() method runs after a Promise settles,
whether it fulfills or rejects. It is useful for cleanup tasks.
const paymentPromise = Promise.resolve("Payment successful!");
paymentPromise
.then((message) => {
console.log(message);
})
.catch((error) => {
console.log(error);
})
.finally(() => {
console.log("Payment process completed.");
});
Output
Payment successful! Payment process completed.
7. Promise Chaining
Promise chaining allows us to perform multiple operations in sequence.
Each then() can return a value or another Promise for
the next step.
Promise.resolve(10)
.then((marks) => {
console.log("Original marks: " + marks);
return marks + 5;
})
.then((total) => {
console.log("Updated marks: " + total);
})
.catch((error) => {
console.log("Error: " + error);
});
Output
Original marks: 10 Updated marks: 15
8. Important Promise Methods
| Method | Purpose |
|---|---|
then() |
Handles fulfillment and can transform the result. |
catch() |
Handles rejection or errors in the chain. |
finally() |
Runs after settlement, regardless of outcome. |
Promise.all() |
Fulfills when all input Promises fulfill; rejects if an input rejects. |
Promise.allSettled() |
Waits until all input Promises settle. |
Promise.race() |
Settles with the first input Promise to settle. |
Promise.any() |
Fulfills with the first fulfilled input Promise, or rejects if all reject. |
9. Important Points to Remember
- A Promise represents the eventual result of an operation.
- Its states are pending, fulfilled, and rejected.
resolve()fulfills a Promise;reject()rejects it.then()handles fulfillment and supports chaining.catch()handles rejection.finally()runs after settlement.- Promises help structure asynchronous operations without deeply nested callbacks.
Summary
In this lesson, we learned how to create Promises, understand Promise states, handle fulfillment and rejection using then() and catch(), use finally(), and chain multiple operations. Examples involving Samadhan, Pradnya, and CIIT Training Institute demonstrate how Promises can represent real-world tasks.