Promises in JavaScript
🔐 What Is a Promise?
A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. Promises make it easier to manage async code and avoid callback hell.
>>“A Promise is a placeholder for a future value.”
📦 States of a Promise
| State | Description |
|---|---|
| pending | The initial state — neither fulfilled nor rejected. |
| fulfilled | Operation completed successfully. |
| rejected | Operation failed. |
🧪 Creating a Promise
Basic Promise Structure
const myPromise = new Promise((resolve, reject) => {
// async operation
if (/* success */) {
resolve("Success!");
} else {
reject("Something went wrong.");
}
});🔗 Consuming a Promise
Use .then() for success and .catch() for error handling.
Using then() and catch()
myPromise
.then((result) => {
console.log("Resolved:", result);
})
.catch((error) => {
console.error("Rejected:", error);
});🕰 Example: Delayed Promise
setTimeout with Promise
function delay(ms) {
return new Promise((resolve) => {
setTimeout(() => {
resolve("Done after " + ms + "ms");
}, ms);
});
}
delay(2000).then(console.log);💥 Promise Rejection
Rejecting a Promise
const brokenPromise = new Promise((_, reject) => {
reject("Oops!");
});
brokenPromise.catch((err) => console.error(err));Note
⚠️ Always handle rejected promises using .catch() or try...catch in async functions.
📚 Promise Chaining
Promises can be chained to run asynchronous operations in sequence.
Chaining Example
fetchData()
.then(processData)
.then(saveData)
.then(() => console.log("All done!"))
.catch((err) => console.error("Error:", err));🔄 Promise.all()
Executes multiple promises in parallel and waits for all of them to resolve or for one to reject.
Using Promise.all()
Promise.all([fetchUser(), fetchPosts(), fetchComments()])
.then(([user, posts, comments]) => {
console.log(user, posts, comments);
})
.catch(console.error);🧙♂️ Modern Way: async/await
Promises work seamlessly with async and await to write cleaner, more readable async code.
Async/Await with Promises
async function run() {
try {
const result = await delay(1000);
console.log(result);
} catch (error) {
console.error(error);
}
}
run();🔗 Further Reading
>>“Promises are not about timing. They’re about trust.”