async function fetchUserData(userId) {
// API endpoint for user data
const url = `https://api.example.com/users/${userId}`;
// Error handling with try/catch
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Failed to fetch user data:', error);
throw error;
}
}
This example shows an asynchronous JavaScript function that fetches user data from an API and includes proper error handling with try/catch blocks.