Promises — then, catch & finally
A Promise represents work that finishes later (API call, file read, timer). ES6 standardized Promises. Node.js and browsers use them everywhere — async/await (next lesson) is built on top.
Three states
- Pending — still running
- Fulfilled — success,
.then()runs - Rejected — error,
.catch()runs
Creating a Promise
function wait(ms) {
return new Promise((resolve) => {
setTimeout(() => resolve('done'), ms);
});
}
wait(1000).then(msg => console.log(msg));
Chaining API-style flow
fetch('https://api.example.com/courses')
.then(res => {
if (!res.ok) throw new Error('HTTP ' + res.status);
return res.json();
})
.then(data => {
console.log('Courses:', data.length);
})
.catch(err => {
console.error('Failed:', err.message);
})
.finally(() => {
console.log('Request finished');
});
🌍 Real-world example — Verify coupon code (simulated)
function validateCoupon(code) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (code === 'LEARN50') resolve({ discount: 50 });
else reject(new Error('Invalid coupon'));
}, 300);
});
}
validateCoupon('LEARN50')
.then(({ discount }) => console.log('Saved', discount + '%'))
.catch(err => console.log(err.message));⚠️ Common Mistake: Forgetting to return inside .then — breaks the chain. Always return the next Promise or value.
💡 Tip: Promise.all([p1, p2]) runs promises in parallel — used when loading dashboard + user profile together.
👨🏫 Teaching note: Draw the Promise state diagram on board before showing async/await — students map await to .then mentally.