JAVASCRIPT
Robust API Data Fetching with Async/Await in JavaScript
Learn to fetch data from REST APIs using modern JavaScript `async/await` syntax, incorporating proper error handling and abort controllers for cleaner, more resilient code.
async function fetchDataFromApi(url, options = {}) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), options.timeout || 8000); // Default 8s timeout
try {
const response = await fetch(url, { ...options, signal: controller.signal });
clearTimeout(timeoutId); // Clear timeout if fetch succeeds
if (!response.ok) {
const errorData = await response.json().catch(() => ({ message: response.statusText }));
throw new Error(`API Error: ${response.status} - ${errorData.message || 'Unknown error'}`);
}
return await response.json();
} catch (error) {
clearTimeout(timeoutId); // Ensure timeout is cleared on error too
if (error.name === 'AbortError') {
console.error('Fetch aborted due to timeout or explicit cancellation:', error.message);
throw new Error('Request timed out or was cancelled.');
}
console.error('Network or API request failed:', error);
throw error; // Re-throw for caller to handle
}
}
// Example usage:
// fetchDataFromApi('https://api.example.com/data', { method: 'GET', timeout: 5000 })
// .then(data => console.log('Fetched data:', data))
// .catch(error => console.error('Failed to fetch:', error.message));
How it works: This snippet demonstrates how to make asynchronous API requests using `fetch` with `async/await`. It includes crucial error handling for network issues, HTTP status codes (`response.ok`), and uses `AbortController` to implement request timeouts, making API calls more robust and preventing hanging requests. This ensures your application can gracefully handle various network and API-related failures.