When JavaScript encounters asynchronous code, it offloads the execution of that code to the browser's event loop. Asynchronous operations like fetching data from an API or waiting for a timer to complete, are handled by registering callback functions or using promises and the async/await syntax to manage the flow of data.
async function fetchData() {
try {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}