JavaScript Promises
What is a Promise?
A Promise represents a value that isn't available yet — it's the result of an asynchronous operation that will eventually resolve or reject.
JavaScript
// A Promise has 3 states: pending → fulfilled OR rejected const promise = new Promise((resolve, reject) => { // Do async work... const success = true; if (success) { resolve("Data loaded!"); // fulfilled } else { reject(new Error("Load failed")); // rejected } });
.then, .catch, .finally
JavaScript
promise .then(data => { console.log(data); // "Data loaded!" }) .catch(error => { console.log(error.message); // if rejected }) .finally(() => { // Runs ALWAYS — success or failure // Good for hiding loading spinners });
Promise Chaining
JavaScript
fetch("/api/user/1") .then(response => response.json()) // parse JSON .then(user => fetch(`/api/posts?userId=${user.id}`)) .then(response => response.json()) .then(posts => console.log(posts)) .catch(err => console.log("Error:", err)); // Each .then receives the return value of the previous
Promise.all — Run in Parallel
JavaScript
// All requests start at the same time — faster than sequential const [user, posts, comments] = await Promise.all([ fetch("/api/user") .then(r => r.json()), fetch("/api/posts") .then(r => r.json()), fetch("/api/comments").then(r => r.json()) ]); // If ANY promise rejects, the whole thing rejects // Promise.allSettled — get results even if some fail const results = await Promise.allSettled([p1, p2, p3]); results.forEach(r => { if (r.status === "fulfilled") console.log(r.value); if (r.status === "rejected") console.log(r.reason); });
Creating Resolved/Rejected Promises
JavaScript
// Instantly resolved const p1 = Promise.resolve("immediate value"); // Instantly rejected const p2 = Promise.reject(new Error("something went wrong")); // Useful in tests or conditional logic function getUser(id) { if (!id) return Promise.reject(new Error("ID required")); return fetch(`/api/users/${id}`).then(r => r.json()); }