Beginner LevelJavaScript & TypeScript
How does async/await work for handling asynchronous JavaScript code?
❓ Interview Prompt: Explain how async/await syntactic sugar builds on Promises and how to handle errors using try/catch blocks.
async/await is syntactic sugar built on top of ES6 Promises, allowing asynchronous code to be written and read like synchronous imperative code.
Key Syntax Rules:
1
`async` functions: Declaring a function
async ensures it automatically returns a Promise (wrapping non-promise returns).2
`await` keyword: Can only be used inside
async functions (or top-level ES modules). Pauses function execution until the promise settles.3
Error Handling: Uses standard
try...catch blocks instead of .catch() callbacks.Code Implementation Example
javascript
async function loadDashboardData(userId) {
try {
// Execution pauses on await until Promise resolves
const response = await fetch(`/api/users/${userId}`);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const user = await response.json();
return user;
} catch (error) {
console.error('Failed to load user:', error.message);
throw error; // Re-throw or handle gracefully
}
}
// Calling async function returns a Promise
loadDashboardData(42).then(user => console.log('Done'));💡Clean asynchronous control flow with async/await and try/catch error handling.
🎯 Interview Key Takeaway
async/await makes asynchronous code read synchronously. Use try/catch blocks to handle promise rejections.
#Async Await#Promises#Error Handling#Beginner
Back to all JavaScript & TypeScript Questions→