Example: Fetch with async/await and try-catch
A comprehensive example demonstrating how to use async/await with fetch API, including proper error handling with try-catch blocks.
Step by step
Key Points:
- try block contains the async operations.
- catch block handles any errors that occur.
- finally block executes regardless of success or failure.
- Proper error checking with response.ok before processing data.
Examples
Fetch Users with Error Handling:
async function fetchUsers() {
const apiUrl = 'https://jsonplaceholder.typicode.com/users';
try {
console.log('Fetching data...');
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const users = await response.json();
console.log('Fetched Users:', users);
} catch (error) {
console.error('Error occurred:', error.message);
} finally {
console.log('Fetch attempt complete.');
}
}
fetchUsers();Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus