Promises (resolve, reject, then, catch)
A Promise represents a value that may be available now, later, or never. It's like an IOU — 'I promise to give you data when the operation completes.' Promises have three states: pending, fulfilled, or rejected.
Promise Basics
- new Promise((resolve, reject) => { }) — Create a promise
- resolve(value) — Operation succeeded. Pass the result
- reject(error) — Operation failed. Pass the error
- promise.then(onSuccess) — Handle fulfilled promise
- .catch(onError) — Handle rejected promise
- States — pending (waiting), fulfilled (resolved), rejected (error). Can only change once
Promises Code
// Creating a Promise
function fetchUser(userId) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (userId > 0) {
resolve({ id: userId, name: "Alice", email: "alice@email.com" });
} else {
reject(new Error("Invalid user ID"));
}
}, 1000);
});
}
// Using a Promise — .then() and .catch()
fetchUser(1)
.then(user => {
console.log("✅ Got user:", user.name);
})
.catch(error => {
console.error("❌ Error:", error.message);
});
// Compare: callback vs promise
// Callback: fetchUser(1, (err, user) => { if (err) ... })
// Promise: fetchUser(1).then(user => ...).catch(err => ...)
// Promise is flatter, cleaner, and easier to chain!
// Real-world: simulating API call
function apiCall(endpoint) {
return new Promise((resolve, reject) => {
console.log(`Fetching ${endpoint}...`);
setTimeout(() => {
if (endpoint.startsWith("/api")) {
resolve({ data: `Response from ${endpoint}`, status: 200 });
} else {
reject(new Error(`404: ${endpoint} not found`));
}
}, 800);
});
}
apiCall("/api/users")
.then(response => console.log("Data:", response))
.catch(error => console.error("Error:", error.message));Tip
Tip
Chain .then() for sequential async operations. Each .then() receives the return value of the previous one. Return a value or Promise from .then() to pass data down the chain.
A Promise settles ONCE — pending → fulfilled OR rejected
Common Mistake
Warning
Forgetting to return inside .then() breaks the chain. Without return, the next .then() receives undefined. Always return values or Promises: .then(data => { return processData(data); }).
Practice Task
Note
Promise practice: (1) Create a Promise that resolves after 2 seconds with a message. (2) Chain 3 .then() calls that each transform the data. (3) Add a .catch() that handles any errors. (4) Add .finally() for cleanup.
Quick Quiz
Key Takeaways
- A Promise represents a value that may be available now, later, or never.
- new Promise((resolve, reject) => { }) — Create a promise
- resolve(value) — Operation succeeded. Pass the result
- reject(error) — Operation failed. Pass the error