What is CallBack?
- It is a function that is passed as an argument to another function
- callback allows another function to call
- A function can accept another function as argument
function greet(name,callback) {
console.log("Hello, " + name);
callback();
}
function sayBye() {
console.log("Goodbye!");
}
greet("Ajay", sayBye);
When to use callback?
- when performing asynchronous operations such as network requests
- It is used to handle events such as user input,mouse clicks
What is CallBack Hell?
Multiple nested callback functions make code more difficult to read and maintain so that we call it as callback hell.
setTimeout(()=>{
console.log("step1");
setTimeout(()=>{
console.log("step2");
setTimeout(()=>{
console.log("step3");
setTimeout(()=>{
console.log("step4")
},1000)
},1000)
},1000)
},1000)
Problems with callback hell:
- Readability
- Error Handling
- Maintaining
Solutions to avoid callback hell
- Promises
- Async/Await
Top comments (0)