JAVASCRIPT
Fetching Data from an API with Async/Await
Learn how to make a basic GET request to an API using JavaScript's modern `fetch` API with `async/await` for clean, readable asynchronous code.
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();
console.log('Fetched Data:', data);
return data;
} catch (error) {
console.error('Error fetching data:', error);
throw error; // Re-throw to allow further handling
}
}
// Example usage:
// fetchData('https://api.example.com/data')
// .then(data => console.log('Successfully processed:', data))
// .catch(err => console.error('Failed to process data:', err));
// Or inside another async function:
// (async () => {
// try {
// const myData = await fetchData('https://jsonplaceholder.typicode.com/todos/1');
// console.log('My specific data:', myData);
// } catch (error) {
// console.error('Caught error during specific data fetch:', error);
// }
// })();
How it works: This snippet demonstrates how to perform a simple GET request to an API endpoint using the `fetch` API coupled with `async/await` for asynchronous operations. It includes basic error checking for network issues and non-OK HTTP responses, parsing the JSON response, and logging the data or error.