Promises
then, catch, finally, Promise.all
Skills taught: js.promises, js.async, js.error-handling
Creating a Promise
// A Promise wraps async work
const fetchUser = new Promise((resolve, reject) => {
// Simulate network delay
setTimeout(() => {
const success = Math.random() > 0.2; // 80% success
if (success) {
resolve({ id: 1, name: 'Prashant' }); // fulfill with data
} else {
reject(new Error('Failed to fetch user')); // reject with error
}
}, 1000);
});
// Use the promise
fetchUser
.then(user => {
console.log('Got user:', user.name);
return user.name.toUpperCase(); // return passes to next .then()
})
.then(upperName => {
console.log('Uppercased:', upperName);
})
.catch(error => {
console.error('Error:', error.message);
})
.finally(() => {
console.log('Done — runs always'); // cleanup: hide spinner, etc.
});
Promise.resolve and Promise.reject
// Already-resolved promise — useful for testing or returning consistent types
const resolved = Promise.resolve({ id: 1, name: 'Ana' });
resolved.then(data => console.log(data)); // { id: 1, name: 'Ana' }
// Already-rejected promise
const rejected = Promise.reject(new Error('Something went wrong'));
rejected.catch(err => console.error(err.message)); // 'Something went wrong'
Promise.all — run in parallel
// Run multiple promises at the same time — wait for ALL to finish
const p1 = fetch('/api/user').then(r => r.json());
const p2 = fetch('/api/posts').then(r => r.json());
const p3 = fetch('/api/comments').then(r => r.json());
Promise.all([p1, p2, p3])
.then(([user, posts, comments]) => {
console.log(user, posts, comments); // all three results
})
.catch(error => {
// Fires if ANY promise rejects
console.error('One failed:', error);
});
// Promise.allSettled — wait for all, even if some fail
Promise.allSettled([p1, p2, p3])
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') console.log('OK:', result.value);
else console.error('Failed:', result.reason);
});
});
Frequently Asked Questions
What happens if I forget .catch()?
An unhandled rejection logs a warning in the console. In Node.js, it can crash the process. Always add .catch() at the end of a chain. async/await makes this easier with try/catch.
What is the difference between Promise.all and Promise.allSettled?
Promise.all rejects immediately if any promise rejects. Promise.allSettled always waits for all promises and returns an array of {status: 'fulfilled'|'rejected', value|reason} — use it when you need all results even if some fail.