Back to Blog
Understanding Promises and Async/Await in JavaScript
Asynchronous programming is a fundamental concept in JavaScript, especially when dealing with operations like API calls, file operations, or any task that might take some time to complete.
Basic Promise Example
javascript
const promise = new Promise((resolve, reject) => {
// Async operation
setTimeout(() => {
const success = true;
if (success) {
resolve('Operation completed!');
} else {
reject('Operation failed!');
}
}, 1000);
});
promise
.then(result => console.log(result))
.catch(error => console.error(error));
Promise States
Pending
Initial state, neither fulfilled nor rejected
Fulfilled
Operation completed successfully
Rejected
Operation failed
Promise Methods
javascript
// Promise.all - waits for all promises to resolve
Promise.all([promise1, promise2, promise3])
.then(results => console.log(results));
// Promise.race - resolves/rejects as soon as one promise does
Promise.race([promise1, promise2, promise3])
.then(result => console.log(result));
// Promise.allSettled - waits for all promises to settle
Promise.allSettled([promise1, promise2, promise3])
.then(results => console.log(results));
Async/Await
Async/await is syntactic sugar over promises, making asynchronous code look and behave more like synchronous code.
javascript
async function fetchUserData() {
try {
const response = await fetch('/api/user');
const data = await response.json();
return data;
} catch (error) {
console.error('Error fetching user:', error);
throw error;
}
}
Key Takeaways
- Always handle errors using try/catch with async/await
- Use Promise.all for parallel operations
- Remember that async functions always return promises
- Consider using Promise.allSettled for multiple independent operations