async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
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('Fetch error:', error.message);
throw error; // Re-throw to allow outer try/catch to handle if needed
}
}
// Usage
fetchData()
.then(data => console.log('Data handled:', data))
.catch(err => console.error('Final error handling:', err.message));
Exemple d'utilisation de `async/await` pour gérer des requêtes HTTP asynchrones avec gestion des erreurs.