JAVASCRIPT
Performing a Basic GET Request with Async/Await
Learn to make an asynchronous GET request to an API using modern JavaScript fetch API, including essential error handling and async/await syntax for cleaner 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 for further handling if needed
}
}
// Usage example:
// fetchData('https://api.example.com/data')
// .then(data => console.log('Successfully got data:', data))
// .catch(error => console.error('Failed to get data:', error));
How it works: This snippet demonstrates how to make a basic GET request to an API using the modern `fetch` API with `async/await` for asynchronous operations. It includes robust error handling: first by checking if the HTTP response status is OK (`response.ok`), and then by catching any network or parsing errors. The response is parsed as JSON, and the fetched data is returned or an error is thrown for the caller to handle.