What is a Promise in JavaScript?
A Promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
It’s like a placeholder for a value that will be available now, later, or never.
Why Promises?
In JavaScript, many operations take time — like fetching data from an API or reading a file. Without Promises, we used callback functions, which often led to "callback hell" — a messy, nested structure of callbacks that was hard to read and maintain.
Promises help handle asynchronous operations in a more readable and manageable way.
Promise States
A Promise has three states:
- Pending – The initial state, neither fulfilled nor rejected.
- Fulfilled – The operation completed successfully.
- Rejected – The operation failed.
+-------------------+
| Pending |
+-------------------+
/ \
/ \
+-------------+ +-------------+
| Fulfilled | | Rejected |
+-------------+ +-------------+
Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve(" Promise fulfilled!");
} else {
reject(" Promise rejected!");
}
});
Consuming a Promise
myPromise
.then((message) => {
console.log(message); // Promise fulfilled!
})
.catch((error) => {
console.log(error); // Promise rejected!
})
.finally(() => {
console.log(" Promise is settled (either fulfilled or rejected)");
});
Callbacks vs. Promises
Callbacks | Promises |
---|---|
Callback hell (nested code) | Cleaner, chainable .then()
|
Harder to manage errors | Error handling via .catch()
|
Less readable | More readable |
Traditional async handling | Modern async handling |
Promise Example with API (Fetch)
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log("Post:", data))
.catch(error => console.log("Error:", error));
Conclusion
Promises are a powerful way to handle asynchronous operations in JavaScript. They make code cleaner, more readable, and easier to manage than traditional callbacks.
Top comments (0)