Asynchronous code in JavaScript is often managed using various techniques to ensure smooth execution and avoid blocking the main thread. Here are some common methods for handling asynchronous code:
-
Callbacks:
The traditional approach where functions accept callbacks that are executed once the asynchronous operation completes.
function fetchData(callback) { // Simulating asynchronous operation setTimeout(() => { const data = 'Some fetched data'; callback(data); }, 1000); } // Using the fetchData function with a callback fetchData((result) => { console.log(result); });
-
Promises:
Introduced in ES6, promises provide a cleaner way to handle asynchronous operations and their results or errors.
function fetchData() { return new Promise((resolve, reject) => { // Simulating asynchronous operation setTimeout(() => { const success = true; if (success) { const data = 'Some fetched data'; resolve(data); } else { reject('Error fetching data'); } }, 1000); }); } // Using promises with then() and catch() fetchData() .then((result) => { console.log(result); }) .catch((error) => { console.error(error); });
-
Async/Await:
Building on top of promises, async functions make asynchronous code look more synchronous and easier to read by using the
async
keyword with functions andawait
keyword within those functions to wait for promises to resolve.async function fetchData() { return new Promise((resolve) => { setTimeout(() => { const data = 'Some fetched data'; resolve(data); }, 1000); }); } // Using async/await async function processData() { try { const result = await fetchData(); console.log(result); } catch (error) { console.error(error); } } processData();
-
Event listeners and callbacks:
For handling asynchronous operations triggered by events, such as user interactions or network events.
const button = document.getElementById('myButton'); button.addEventListener('click', () => { // Perform asynchronous operation });
These techniques help in managing asynchronous code by providing structured ways to handle the completion or failure of asynchronous tasks, improving readability and maintainability in JavaScript applications.