In JavaScript, handling asynchronous operations and callbacks can be done using various methods. Here are some common approaches:
Example:
function fetchData(callback) {
setTimeout(function() {
// Simulating asynchronous operation
const data = 'Some data';
callback(data);
}, 2000);
}
fetchData(function(data) {
console.log(data);
});
Example:
function fetchData() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
// Simulating asynchronous operation
const data = 'Some data';
resolve(data);
}, 2000);
});
}
fetchData()
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.error(error);
});
async
keyword is used to define an asynchronous function, and the await
keyword is used to wait for a promise to resolve.Example:
async function fetchData() {
return new Promise(function(resolve, reject) {
setTimeout(function() {
// Simulating asynchronous operation
const data = 'Some data';
resolve(data);
}, 2000);
});
}
async function fetchDataAndLog() {
try {
const data = await fetchData();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchDataAndLog();
These are some popular ways to handle asynchronous operations and callbacks in JavaScript. You can choose the approach that best suits your needs and coding style.