Async/await makes working with promises much easier and your asynchronous code look more like synchronous code.
Basic Usage
// Traditional promise approach
function fetchUser() {
return fetch('https://api.example.com/user')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
}
// Using async/await
async function fetchUser() {
try {
const response = await fetch('https://api.example.com/user');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
Multiple Async Operations
async function getAllData() {
try {
// Sequential execution
const user = await fetch('/api/user').then(r => r.json());
const posts = await fetch(`/api/posts/${user.id}`).then(r => r.json());
// Parallel execution (faster!)
const [userData, postsData] = await Promise.all([
fetch('/api/user').then(r => r.json()),
fetch('/api/posts').then(r => r.json())
]);
return { userData, postsData };
} catch (error) {
console.error('Error fetching data:', error);
}
}
Always remember to use try/catch blocks for proper error handling!