Write an async function that fetches data from an API endpoint and logs the email property from the returned JSON object.
JavaScript provides the fetch
API to make network requests and work with external data sources.
You can fetch data from a URL and handle the response using promises.
Example: Fetch user data from a placeholder API
fetch('https://jsonplaceholder.typicode.com/users/1')
.then(response => response.json())
.then(data => {
console.log(data.name);
})
.catch(error => {
console.error('Error:', error);
});
You can also use async functions for cleaner, easier-to-read asynchronous code.
async function getUser() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/1');
const data = await response.json();
console.log(data.name);
} catch (error) {
console.error('Error:', error);
}
}
getUser();