What is a Promise?
A Promise represents the eventual result of an asynchronous operation. It's either fulfilled (has a value) or rejected (has an error). Promises solve callback hell with a chainable API.
// Create a promise:
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.5) resolve("Success!");
else reject(new Error("Failed"));
}, 1000);
});
// Consume it:
promise
.then(value => console.log("Got:", value))
.catch(err => console.error("Error:", err.message))
.finally(() => console.log("Done either way"));
// Promise chaining:
fetch("/api/user")
.then(res => res.json())
.then(user => fetch("/api/posts?userId=" + user.id))
.then(res => res.json())
.then(posts => console.log(posts))
.catch(err => console.error(err));
Promise Static Methods
// Promise.resolve/reject — instant promises:
Promise.resolve(42).then(console.log); // 42
// Promise.all — parallel, fails if any fails:
const [users, posts] = await Promise.all([
fetch("/api/users").then(r => r.json()),
fetch("/api/posts").then(r => r.json())
]);
// Both requests run simultaneously!
// Promise.allSettled — parallel, never fails:
const results = await Promise.allSettled([p1, p2, p3]);
results.forEach(r => {
if (r.status === "fulfilled") console.log(r.value);
else console.error(r.reason);
});
// Promise.race — first settled wins:
const fastest = await Promise.race([fetch("/primary"), fetch("/backup")]);
// Promise.any — first fulfilled wins (ignores rejections):
const firstSuccess = await Promise.any([p1, p2, p3]);
// Promisify a callback:
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
await delay(1000); // pause 1 second
⚡ Key Takeaways
- 3 states: pending, fulfilled, rejected — once settled, immutable
- .then() handles success, .catch() handles errors, .finally() always runs
- Promise.all() for parallel — fails fast if any reject
- Promise.allSettled() for parallel — never fails, reports all outcomes
- Promise.race() for timeouts and redundant requests
- Always .catch() unhandled rejections — they cause warnings/crashes
🎯 Practice Exercises
EXERCISE 1
Use Promise.all() to fetch data from 3 different JSONPlaceholder endpoints simultaneously. Measure the time savings vs sequential fetching.
EXERCISE 2 — CHALLENGE
Implement Promise.all() from scratch. It should accept an array of promises and resolve with an array of values when all resolve, or reject immediately when any one rejects.