Async/await makes working with promises 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:', error);
}
}
Error Handling Patterns
async function robustFetch(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(\`HTTP error! status: \${response.status}\`);
}
return await response.json();
} catch (error) {
console.error('Fetch error:', error);
return null;
}
}
Async Iteration
async function processArray(array) {
for (const item of array) {
await processItem(item);
}
}
// Process in parallel
async function processArrayParallel(array) {
await Promise.all(array.map(item => processItem(item)));
}
Always use try/catch blocks and consider parallel execution for better performance!