🤝 Promises = Async Operations
Callback hell is ugly. Promises make async code elegant. Chain, catch, await — async made easy.
❌ Callback Hell
getUser(function(user) {
getOrders(user, function(orders) {
getDetails(orders, function(details) {
console.log(details);
});
});
});
✅ Promise Chain
getUser()
.then(user => getOrders(user))
.then(orders => getDetails(orders))
.then(details => console.log(details))
.catch(err => console.error(err));
📝 Promise Methods
// Creating a promise
const myPromise = new Promise((resolve, reject) => {
// Async operation
if (success) {
resolve(result);
} else {
reject(error);
}
});
// Using a promise
myPromise
.then(result => {
console.log('Success:', result);
return processedData;
})
.then(processed => {
console.log('Processed:', processed);
})
.catch(error => {
console.error('Error:', error);
})
.finally(() => {
console.log('Always runs');
});
// Promise.all (parallel)
const promises = [
fetch('/api/user'),
fetch('/api/orders'),
fetch('/api/products')
];
Promise.all(promises)
.then(responses => Promise.all(responses.map(r => r.json())))
.then(data => {
const [user, orders, products] = data;
console.log('All data loaded:', { user, orders, products });
})
.catch(error => console.error('One failed:', error));
// Promise.allSettled (wait for all)
Promise.allSettled(promises)
.then(results => {
results.forEach(result => {
if (result.status === 'fulfilled') {
console.log('Success:', result.value);
} else {
console.log('Failed:', result.reason);
}
});
});
// Promise.race (first to complete)
Promise.race([
fetch('/api/primary'),
fetch('/api/backup')
])
.then(response => response.json())
.then(data => console.log('First response:', data));
💡 Promise Tips
- Always catch errors
- Use Promise.all for parallel
- Use async/await for readability
- Avoid nesting (use chaining)
- Handle rejected promises
“Promises make async elegant. Chain operations, handle errors. Essential for modern JavaScript.”
