Ask any question about JavaScript here... and get an instant response.
How does JavaScript handle asynchronous operations?
Asked on Jun 29, 2025
Answer
JavaScript handles asynchronous operations using mechanisms like callbacks, promises, and async/await, allowing non-blocking execution. Here's a simple example using promises:
<!-- BEGIN COPY / PASTE -->
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = { message: "Hello, world!" };
resolve(data);
}, 1000);
});
}
fetchData()
.then(response => {
console.log(response.message);
})
.catch(error => {
console.error("Error:", error);
});
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "fetchData" function returns a promise that resolves after 1 second.
- "setTimeout" simulates an asynchronous operation.
- ".then" is used to handle the resolved value of the promise.
- ".catch" is used to handle any potential errors.
- Promises provide a cleaner way to handle asynchronous operations compared to traditional callbacks.
Recommended Links:
