JAVASCRIPT
Fetch Data from a REST API with Async/Await
Learn to asynchronously fetch data from a REST API using modern JavaScript async/await syntax for clean, readable API integrations in web applications.
async function fetchDataFromApi(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 caller to handle
}
}
// Example usage:
// fetchDataFromApi('https://api.example.com/items')
// .then(data => console.log('Successfully processed:', data))
// .catch(error => console.log('Failed to fetch/process.'));
How it works: This JavaScript snippet demonstrates how to fetch data from a REST API using `async/await`. The `fetchDataFromApi` function takes a URL, performs an asynchronous request, and parses the JSON response. It includes error handling for network issues or non-OK HTTP responses, making API calls robust and easier to manage with modern syntax.