Async Await in JavaScript
Async/Await
Syntactic sugar over Promises for cleaner async code.
Async Await Example
async function getUserData(userId) {
try {
const response = await fetch(`/api/users/${userId}`);
const userData = await response.json();
return userData;
} catch (error) {
console.error("Fetch error:", error);
throw error;
}
}
getUserData(1).then(user => console.log(user));Key Points
asyncfunctions always return Promise.awaitpauses execution until Promise settles.- try/catch for error handling.
- Sequential async operations look synchronous.