Callback hell issue in JavaScript
Suppose we want to use the loadImage
function to load three images:
loadImage('img1.png', function(image, err) {
document.body.append(image);
});
loadImage('img2.png', function(image, err) {
document.body.append(image);
});
loadImage('img3.png', function(image, err) {
document.body.append(image);
});
There is something wrong with this code. The
fact is that the images will be appended to
body
as they are loaded. That is,
no one guarantees us that the images
will be added in the exact order that
we need.
There is something else. Let's say we want to do something when all the three images are loaded. In our code, we simply won't be able to catch this moment, because all the three images are loaded independently.
Ok. Let's change the code:
loadImage('img1.png', function(image1, err1) {
document.body.append(image1);
loadImage('img2.png', function(image2, err2) {
document.body.append(image2);
loadImage('img3.png', function(image3, err3) {
document.body.append(image3);
console.log('all images uploaded');
});
});
});
We have solved both of the described problems. However, we are faced with another. While it is still not very obvious, but imagine how our code will look like if it loads not three, but, let's say, ten images, plus an exception handling is added. As a result, the code will become extremely unreadable: a code complexity increases like an avalanche when callbacks are nested. This situation is called callback hell.
Rewrite the above code to load
10
images plus a handle
exceptions. Make sure you get
a callback hell situation.