Explain async/await syntax and how it relates to Promises. What are the benefits and potential pitfalls?
3 minintermediatejavascriptes6asyncawaitsyntaxrelates
Quick Answer
Async/await is syntactic sugar built on top of Promises, making asynchronous code look and behave more like synchronous code.
Detailed Answer
Explain async/await syntax and how it relates to Promises. What are the benefits and potential pitfalls?
Async/await is syntactic sugar built on top of Promises, making asynchronous code look and behave more like synchronous code.
Basic Syntax:
// Promise-based
function fetchUser(id) {
return fetch(`/api/users/${id}`)
.then(response => response.json())
.then(user => {
console.log(user);
return user;
})
.catch(error => {
console.error('Error:', error);
throw error;
});
}
// Async/await equivalent
async function fetchUser(id) {
try {
const response = await fetch(`/api/users/${id}`);
const user = await response.json();
console.log(user);
return user;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
Key Benefits:
- Readability: Easier to read than promise chains
- Error Handling: Better error handling with try/catch
- Debugging: Easier to debug with stack traces
Common Pitfalls:
// ❌ Sequential (slow)
async function fetchSequential() {
const user = await fetchUser(1); // Wait 100ms
const posts = await fetchPosts(1); // Wait 200ms
const comments = await fetchComments(1); // Wait 150ms
// Total: 450ms
}
// ✅ Parallel (fast)
async function fetchParallel() {
const [user, posts, comments] = await Promise.all([
fetchUser(1), // All start simultaneously
fetchPosts(1), // All start simultaneously
fetchComments(1) // All start simultaneously
]);
// Total: 200ms (longest operation)
}
// ❌ Missing await
async function badExample() {
const user = fetchUser(1); // Returns Promise, not user data
console.log(user.name); // Error: Cannot read property 'name' of undefined
}
// ✅ Correct
async function goodExample() {
const user = await fetchUser(1); // Waits for Promise to resolve
console.log(user.name); // Works correctly
}
Error Handling:
async function fetchWithRetry(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
const response = await fetch(url);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (error) {
if (i === maxRetries - 1) throw error;
await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
}
}
}