Callback Hell:
Callback Hell is a situation in JavaScript where multiple nested callback functions make your code look like itβs been through a blender on the highest setting.
This typically occurs when dealing with asynchronous operations, such as making API requests or handling file I/O, where one operation depends on the result of another or previous One.
A callback is simply a function passed as an argument to another function. It gets executed after the first function finishes its work.
Callback Hell (Pyramid of Doom):
login(function () {
selectFood(function () {
makePayment(function () {
placeOrder(function () {
deliverFood(function () {
console.log("Enjoy your meal!");
});
});
});
});
});
login()
|
selectFood()
|
makePayment()
|
placeOrder()
|
deliverFood()
|
Enjoy Meal
Solution to Callback Hell
Promises.
Promise:
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.
A Promise is in one of these states:
- pending: initial state, neither fulfilled nor rejected.
- fulfilled: meaning that the operation was completed successfully.
- rejected: meaning that the operation failed.
The eventual state of a pending promise can either be fulfilled with a value or rejected with a reason (error). When either of these options occur, the associated handlers queued up by a promise's then method are called. If the promise has already been fulfilled or rejected when a corresponding handler is attached, the handler will be called, so there is no race condition between an asynchronous operation completing and its handlers being attached.
Solution for callback hell using promise
login()
.then(selectFood)
.then(makePayment)
.then(placeOrder)
.then(deliverFood)
.then(() => {
console.log("Enjoy your meal!");
})
.catch((error) => {
console.log(error);
});
Example 1:
function tossCoin(){
return new Promise((resolve,reject) => {
const rand = Math.floor(Math.random() * 2)
if(rand==0)
resolve()
else
reject()
})
}
tossCoin()
.then(()=>console.log("Congrats!,Its head,You won"))
.catch(()=>console.log("Sorry,You lost,Its tail"))
Output:
If it is 0 means that is heads.
Congrats!,Its head,You won
Example 2:
function tossCoin(){
return new Promise((resolve,reject) => {
const rand = Math.floor(Math.random() * 2)
if(rand==1)
resolve()
else
reject()
})
}
tossCoin()
.then(()=>console.log("Congrats!,Its head,You won"))
.catch(()=>console.log("Sorry,You lost,Its tail"))
Output:
If it is 1 means that is tail
Sorry,You lost,Its tail
Promise concurrency
The Promise class offers four static methods to facilitate async task concurrency:
Promise.all()
Fulfills when all of the promises fulfill; rejects when any of the promises rejects.
Promise.allSettled()
Fulfills when all promises settle.
Promise.any()
Fulfills when any of the promises fulfills; rejects when all of the promises reject.
Promise.race()
Settles when any of the promises settles. In other words, fulfills when any of the promises fulfills; rejects when any of the promises rejects.
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://www.geeksforgeeks.org/javascript/what-to-understand-callback-and-callback-hell-in-javascript/
https://medium.com/@raihan_tazdid/callback-hell-in-javascript-all-you-need-to-know-296f7f5d3c1


Top comments (0)