- Courses
- 💻Programming Languages
- 🌐JavaScript
- Asynchronous JavaScript
- Promises
On this page
JavaScript Promises
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
A Promise is a robust object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Historically, developers relied on callbacks to handle asynchronous logic, but as applications grew, this led to "callback hell"—deeply nested, unreadable code. Promises resolve this by providing a cleaner, more manageable "contract" for asynchronous actions.
The Lifecycle of a Promise
When a Promise is created, it follows a specific lifecycle. A Promise can only settle once; after it moves from its initial state to a final state, it cannot change again.
- Pending: The initial state. The asynchronous operation has started but has not yet finished or failed.
- Fulfilled (Resolved): The operation completed successfully. The Promise now holds the resulting data.
- Rejected: The operation failed. The Promise holds an error object or a reason for the failure.
Creating a Promise
To generate a Promise, you use the new Promise constructor. This constructor requires an executor function, which runs immediately. The executor receives two arguments: resolve and reject.
resolve(value): Invoked when the task is successful.reject(error): Invoked when the task fails.
const deliveryStatus = new Promise((resolve, reject) => {
const isDelivered = true;
// Simulating a delay for a delivery
setTimeout(() => {
if (isDelivered) {
resolve("Package has arrived.");
} else {
reject("Delivery failed due to weather.");
}
}, 2000);
});
Consuming Promises: .then() and .catch()
Once a Promise is created, you need mechanisms to handle the result when it eventually arrives. These are known as consumer methods.
The .then() Handler
The .then() method is used to handle a fulfilled Promise. It accepts a callback function that receives the value passed into the resolve() function.
The .catch() Handler
The .catch() method handles rejections. It acts as a centralized error handler, catching any issues that occurred during the Promise's execution or within the chain itself.
deliveryStatus
.then((message) => {
console.log("Success: " + message);
})
.catch((error) => {
console.error("Issue: " + error);
});
The .finally() Handler
The .finally() method executes regardless of the outcome. It is commonly used for cleanup tasks, such as hiding a loading spinner on a webpage once a data request is finished.
Promise Chaining
One of the most significant advantages of Promises is the ability to chain operations. Because each .then() call returns a new Promise, you can perform a sequence of asynchronous steps in a flat, vertical structure.
fetchUser(1)
.then((user) => getProfile(user.id))
.then((profile) => getSettings(profile.settingsId))
.then((settings) => {
console.log("User settings loaded:", settings);
})
.catch((err) => {
console.error("An error occurred at some point in the chain:", err);
});
In this example, if any of the three functions (fetchUser, getProfile, or getSettings) fails, the code will skip the remaining .then() blocks and immediately jump to the .catch() block. This is a massive improvement over callbacks, where error checking had to be performed manually at every level of nesting.
Professional Best Practices
- Always Catch: Never leave a Promise without a
.catch()block. Unhandled rejections can cause applications to crash or behave unpredictably. - Return in the Chain: When chaining, always
returnthe next Promise or value from within your.then()block to ensure the data flows correctly to the next step. - Avoid the "Old" Way: Whenever you find yourself nesting a Promise inside another Promise's
.then()block, you are creating a "Promise Pyramid." Flatten it by returning the inner Promise and adding another.then()to the outer chain.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Callbacks
Next
Async/Await
-
The Lifecycle of a Promise
-
Creating a Promise
-
Consuming Promises:
.then()and.catch()- The
.then()Handler - The
.catch()Handler - The
.finally()Handler
- The
-
Promise Chaining
-
Professional Best Practices
