Example: Fetch with async/await and try-catch
Topic 8JavaScript Part 2 (Async JS)
Example: Fetch with async/await and try-catch
Introduction
A comprehensive example demonstrating how to use async/await with fetch API, including proper error handling with try-catch blocks.
Step-by-Step Explanation
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();Interview guide discussion
(0)Join the discussion — login to comment and help other developers.
Login to comment