Callback Hell In JavaScript :
✍ When a function is passed as an argument to another function, it becomes a callback function. This process continues and there are many callbacks inside another's Callback function. The code grows horizontally instead of vertically .That mechanism is known as callback hell.
Callback Hell (Pyramid of Doom) , occurs in asynchronous programming when multiple callbacks are nested within one another . This pattern emerges when each asynchronous operation requires a callback function, and these callbacks contain further asynchronous operations that also need callbacks.
✍ Explanation :
createOrder Function:
- When the createOrder function is called, a callback function is passed into it.
- Example: createOrder(() => {}).
- Inside createOrder, this callback function is executed after completing the createOrder operation.
- By using this callback function, you can call paymentOfOrder inside the callback after createOrder is done.
paymentOfOrder Function:
- When the paymentOfOrder function is called, a callback function is passed into it.
- Example: paymentOfOrder(() => {}).
- Inside paymentOfOrder, this callback function is executed after completing the payment operation.
- By using this callback function, you can call orderSummary inside the callback after paymentOfOrder is done.
orderSummary Function:
- When the orderSummary function is called, a callback function is passed into it.
- Example: orderSummary(() => {}).
- Inside orderSummary, this callback function is executed after completing the summary operation.
- By using this callback function, you can call updateWallet inside the callback after orderSummary is done.
Complete Flow with Explanations
Here’s the complete flow with these explanations applied:
This expanded explanation should clarify how each function's callback is used to invoke the next function in the sequence, demonstrating the flow of execution and how callback functions are passed and executed at each step.
This nesting of callbacks is what leads to callback hell as it makes the code harder to read and maintain, especially as the number of nested operations grows.
Avoid callback hell, consider refactoring the code using Promises or async/await for better readability and maintainability, as previously demonstrated.
Next Blog will be Promises , How we solve the call back issue by promises.
Keep following . Thank You
Top comments (0)