You can retrieve the result of an asynchronous operation in JavaScript using Promises or async/await.
1. Using Promises:
fetch('https://api.example.com/data')
.then(response => response.json()) // Process the response
.then(data => console.log(data)) // Handle the data
.catch(error => console.error('Error:', error)); // Handle errors
2. Using async/await (Preferred for readability):
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data'); // Wait for fetch
const data = await response.json(); // Wait for JSON parsing
console.log(data); // Use the data
} catch (error) {
console.error('Error:', error); // Handle errors
}
}
fetchData();