How does JavaScript handle asynchronous operations?
Asked on Jul 10, 2024
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:
← Back to All Questions