![]() |
VOOZH | about |
Callback Hell happens when multiple dependent asynchronous callbacks are nested, leading to complex and hard-to-manage code that reduces readability and maintainability.
JavaScript handles asynchronous tasks in the background using callbacks, but chaining many dependent operations can make the code complex and hard to manage.
We should break down the code into small parts and reusable functions. This will reduce the depth of nesting of the function making it easier to understand.
function getData(callback) {
getDataFromAPI(callback);
}
function parseAndProcessData(data, callback) {
parseData(data, function (parsedData) {
processData(parsedData, callback);
});
}
getData(function (data) {
parseAndProcessData(data, function (finalData) {
saveData(finalData, function (savedData) {
sendEmail(savedData, function (response) {
console.log('Email sent!', response);
});
});
});
});
Promises can help handle the asynchronous code. Promises represent the failure of an asynchronous operation.
getDataFromAPI()
.then(parseData)
.then(processData)
.then(saveData)
.then(sendEmail)
.then(response => {
console.log('Email sent!', response);
})
.catch(error => {
console.error('Error:', error);
});
Async/Await was introduced in ES8, which simplifies the syntax for working the promises. With async/await, we can write asynchronous code that looks like synchronous code, making it more readable and easier to manage.
async function handleData() {
try {
const data = await getDataFromAPI();
const parsedData = await parseData(data);
const processedData = await processData(parsedData);
const savedData = await saveData(processedData);
const response = await sendEmail(savedData);
console.log('Email sent!', response);
} catch (error) {
console.error('Error:', error);
}111111111111111111
}
handleData();