**Promises** solved callback hell. A Promise is an object representing an **asynchronous operation** that will eventually succeed (resolved) or fail (rejected). Chain `.then()` for success and `.catch()` for errors. Promises are always asynchronous — `.then()` callbacks never run synchronously.
1Understanding Promises
Promises solved callback hell. A Promise is an object representing an asynchronous operation that will eventually succeed (resolved) or fail (rejected). Chain .then() for success and .catch() for errors. Promises are always asynchronous — .then() callbacks never run synchronously.
Promise.all() runs promises in parallel and fails fast. Promise.allSettled() runs all and gives all results regardless of failures.
function fetchUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: 'Alice' });
else reject(new Error('Invalid ID'));
}, 500);
});
}
fetchUser(1)
.then(user => console.log(user.name))
.catch(e => console.error(e.message));2Practical Example
Here is a real-world application of Promises showing how it is used in production JavaScript code.
// Promise combinators
const p1 = fetch('/api/users');
const p2 = fetch('/api/posts');
const p3 = fetch('/api/comments');
// Run all in parallel
Promise.all([p1, p2, p3])
.then(([users, posts, comments]) => { /* all 3 done */ })
.catch(e => console.error('At least one failed:', e.message));3Best Practices
Follow these guidelines when working with Promises:
1. Always add .catch() or a rejection handler
2. Return Promises from async functions
3. Use Promise.allSettled() when you need all results even if some fail
Tip: Promise.all() runs promises in parallel and fails fast. Promise.allSettled() runs all and gives all results regardless of failures.
function fetchUser(id) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (id > 0) resolve({ id, name: 'Alice' });
else reject(new Error('Invalid ID'));
}, 500);
});
}
fetchUser(1)
.then(user => console.log(user.name))
.catch(e => console.error(e.message));