π¦ JavaScript Promises
A Promise is a special JavaScript object that represents a value that may be available now, later, or never. Itβs a cleaner alternative to deeply nested callbacks and is commonly used for asynchronous operations like API requests.
π οΈ Creating a Promise
const myPromise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("β
Success!");
} else {
reject("β Failed!");
}
});
π Consuming a Promise
myPromise
.then(result => console.log(result)) // Success handler
.catch(error => console.error(error)) // Error handler
.finally(() => console.log("Done!")); // Always runs
β³ Real Example: Simulate API Delay
function fetchData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve("π‘ Data received after 2 seconds");
}, 2000);
});
}
fetchData().then(data => console.log(data));
π Promise States
- Pending: Initial state, neither fulfilled nor rejected.
- Fulfilled: The operation completed successfully.
- Rejected: The operation failed.
π Chaining Promises
fetchUser()
.then(user => fetchPosts(user.id))
.then(posts => fetchComments(posts[0].id))
.then(comments => console.log(comments))
.catch(error => console.error("Error:", error));
π‘ Tip: Promises allow you to write async logic in a more structured and maintainable way.