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().
Written by Shaikh Abdul Shahid
A Full-Stack Developer with experience in PHP, Laravel, JavaScript, and React.
Founder of Online Learner, sharing practical knowledge and programming tutorials.
Building and maintaining real-world web applications since 2017.
Your Feedback
Help us improve by sharing your thoughts
Online Learner helps developers master programming, database concepts, interview preparation, and real-world implementation through structured learning paths.
Quick Links
© 2023 - 2026 OnlineLearner.in | All Rights Reserved.
