⚡ Promises = Async Made Easy
Async code can be hard to manage. Promises and Async/Await make asynchronous code clean and manageable.
📝 Promise Patterns
// Creating a Promise
const fetchData = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
try {
const data = { id: 1, name: 'John' };
resolve(data);
} catch (error) {
reject(error);
}
}, 1000);
});
};
// Using Promise
fetchData()
.then(data => console.log(data))
.catch(error => console.error(error))
.finally(() => console.log('Done'));
// Promise Chain
fetchData()
.then(data => processData(data))
.then(result => saveData(result))
.then(saved => console.log('Saved!'))
.catch(error => handleError(error));
// Promise.all
const promises = [
fetch('/api/users'),
fetch('/api/posts'),
fetch('/api/comments')
];
Promise.all(promises)
.then(responses => Promise.all(responses.map(r => r.json())))
.then(data => console.log(data))
.catch(error => console.error(error));
// Promise.race
const slowOperation = new Promise(resolve => setTimeout(resolve, 5000));
const timeout = new Promise((_, reject) =>
setTimeout(reject, 3000, 'Operation timed out')
);
Promise.race([slowOperation, timeout])
.then(result => console.log(result))
.catch(error => console.error(error));
🎯 Async/Await Patterns
// Basic Async/Await
async function getData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
// Parallel Operations
async function getDashboardData() {
const [users, posts, stats] = await Promise.all([
fetchUsers(),
fetchPosts(),
fetchStats()
]);
return { users, posts, stats };
}
// Sequential Operations
async function processItems(items) {
const results = [];
for (const item of items) {
const result = await processItem(item);
results.push(result);
}
return results;
}
// Error Handling
async function safeOperation() {
try {
return await operation();
} catch (error) {
if (error.code === 'NETWORK_ERROR') {
return fallbackData();
}
throw error;
}
}
// Retry Pattern
async function retryOperation(operation, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
return await operation();
} catch (error) {
if (i === retries - 1) throw error;
await sleep(Math.pow(2, i) * 1000);
}
}
}
💡 Promise Tips
- Use async/await for readability
- Handle errors with try/catch
- Use Promise.all for parallel operations
- Use Promise.race for timeouts
- Always handle rejections
Promises and async/await make asynchronous code clean and manageable. They're essential for modern JavaScript.
