Asynchronous JavaScript
Callbacks & Callback Hell
Callbacks are functions passed as arguments to other functions and executed later. Too many nested callbacks can lead to callback hell.
- Callbacks allow async operations but can lead to deeply nested, hard-to-read code.
- Callback hell occurs when multiple callbacks are nested, making the code difficult to maintain.
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 1000);
}
fetchData((response) => {
console.log(response); // "Data received"
});
// Callback hell example
function step1(next) {
setTimeout(() => {
console.log("Step 1");
next();
}, 1000);
}
function step2(next) {
setTimeout(() => {
console.log("Step 2");
next();
}, 1000);
}
// Nested callbacks (callback hell)
step1(() => {
step2(() => {
console.log("All steps completed");
});
});