JAVASCRIPT
Fetching Data from a REST API with Async/Await in JavaScript
Learn how to asynchronously fetch JSON data from a REST API using the modern Fetch API with async/await syntax in JavaScript, including basic error handling.
async function fetchData(url) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error)
{
console.error("Failed to fetch data:", error);
throw error; // Re-throw for further handling
}
}
// Example usage:
// fetchData('https://jsonplaceholder.typicode.com/todos/1')
// .then(data => console.log('Fetched data:', data))
// .catch(error => console.error('Error in example usage:', error));
// fetchData('https://invalid.url/nonexistent')
// .catch(error => console.error('Error handling example:', error));
How it works: This JavaScript snippet demonstrates how to fetch data from a REST API using the `fetch` API combined with `async/await` for cleaner asynchronous code. It includes basic error handling for network issues and non-OK HTTP responses, parsing the JSON response, and returning the data, making it a fundamental pattern for client-side API integrations.