What are Promises in JavaScript?
A Promise is an object representing the eventual result of an asynchronous operation — a placeholder for a value that isn't ready yet.
It is always in one of three states:
Pending — not yet settled.
Fulfilled — completed successfully with a value.
Rejected — failed with a reason.
You react with .then() for success, .catch() for errors, and .finally() for cleanup. Promises chain, and each .then() returns a new promise.
Why they exist: Promises replace nested callbacks ("callback hell") with flat, readable chains and unified error handling.
// Creating a Promise
function fetchUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: 'John' });
else reject(new Error('Invalid ID'));
}, 1000);
});
}
// Chaining
fetchUser(1)
.then(user => fetchOrders(user.id)) // Returns a promise
.then(orders => processOrders(orders))
.catch(err => console.error('Error:', err.message))
.finally(() => console.log('Done'));
// Promise.all — parallel, fail-fast
const [user, posts, comments] = await Promise.all([
fetchUser(1),
fetchPosts(1),
fetchComments(1)
]); // All run concurrently
// Promise.allSettled — all complete regardless
const results = await Promise.allSettled([
fetchUser(1),
fetchUser(-1) // This fails but doesn't cancel others
]);
results.forEach(r => {
if (r.status === 'fulfilled') console.log(r.value);
else console.log('Failed:', r.reason);
});
// Promise.race — first to settle wins
const fastest = await Promise.race([
fetchFromServer1(),
fetchFromServer2()
]);new Promise wraps async work with resolve/reject. .then chains transformations, .catch handles any error in the chain, .finally always runs. Promise.all runs in parallel and fails if any promise rejects.
Promise.allSettled waits for all regardless of individual failures. Promise.race returns whichever settles first.
Know all three states (pending, fulfilled, rejected). Show chaining (callback hell solution).
Know all four static methods: all (parallel, fail-fast), allSettled (all complete), race (first settled), any (first fulfilled). Promise.allSettled is often missed.