A Promise is a JavaScript object that represents the eventual completion or failure of an asynchronous operation and its resulting value.
Think of it as a placeholder for a value that will be available in the future.
✅ Why Were Promises Introduced? (Problem They Solve)
Before Promises, JavaScript relied on callbacks, which caused:
- Callback Hell (deeply nested code)
- Hard-to-read logic
- Difficult error handling
- No clear way to chain async operations
Promises solve this by providing:
- Chaining (
.then()) - Centralized error handling (
.catch()) - Better readability and control flow
✅ Promise States
A Promise can be in one of three states:
- Pending – initial state, not fulfilled or rejected
- Fulfilled – operation completed successfully
- Rejected – operation failed
Once fulfilled or rejected, the state is final.
🧪 Creating a Promise
const promise = new Promise((resolve, reject) => {
const success = true;
if (success) {
resolve("Data loaded");
} else {
reject("Error occurred");
}
});
🧪 Consuming a Promise
promise
.then(result => console.log(result))
.catch(error => console.error(error))
.finally(() => console.log("Done"));
🔥 How Promises Work (Behind the Scenes)
- Promise is created → pending
- Async operation runs (API call, timeout)
resolve()→ Promise becomes fulfilledreject()→ Promise becomes rejected.then()or.catch()is executed- Handled via microtask queue in the event loop
🔗 Promise Chaining
fetch("/user")
.then(res => res.json())
.then(user => fetch(`/posts/${user.id}`))
.then(res => res.json())
.then(posts => console.log(posts))
.catch(err => console.error(err));
✔ Clean sequential async flow
✔ No nesting
🧠 Promise Utilities
Promise.all() // wait for all promises
Promise.race() // first resolved/rejected
Promise.any() // first fulfilled
Promise.allSettled() // all results
🎯 Short Interview Answer
Promises are objects that represent the eventual result of an asynchronous operation.
They solve callback hell by allowing clean chaining of async tasks and centralized error handling.
Promises can be pending, fulfilled, or rejected, and they work through the event loop using the microtask queue.