What is a Promise in JavaScript?
A Promise in JavaScript is an object representing the eventual completion (or failure) of an asynchronous operation. It allows you to handle asynchronous tasks more cleanly than callbacks, avoiding "callback hell" and improving code readability.
How Promises Work
A Promise has three states:
- Pending – Initial state (neither fulfilled nor rejected).
- Fulfilled – Operation completed successfully.
- Rejected – Operation failed.
Basic Syntax
const myPromise = new Promise((resolve, reject) => {
// Async operation (e.g., API call, file read)
if (success) {
resolve("Operation succeeded!");
} else {
reject("Operation failed!");
}
});
myPromise
.then((result) => console.log(result))
.catch((error) => console.error(error));
Why Use Promises?
✔ Avoid Callback Hell – Flatter, more readable code.
✔ Better Error Handling – .catch()
centralizes error management.
✔ Chainable – Multiple async operations can be sequenced with .then()
.
Promise Methods
Promise.all()
– Waits for all promises to resolve.Promise.race()
– Returns the first settled promise.Promise.allSettled()
– Waits for all promises to complete (success or failure).
Async/Await: A Cleaner Alternative
Modern JavaScript uses async/await
with Promises for even cleaner syntax:
async function fetchData() {
try {
const response = await fetch('https://api.example.com');
const data = await response.json();
console.log(data);
} catch (error) {
console.error("Fetch failed:", error);
}
}
Common Mistakes
❌ Forgetting .catch()
(unhandled rejections crash apps).
❌ Nesting Promises (use chaining instead).
❌ Ignoring return
in .then()
.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Terms Disclaimer About Us Contact Us
Copyright 2023-2025 © All rights reserved.