Async images loading in a loop in JavaScript

Let the paths to images be stored in an array:

let arr = ['img1.png', 'img2.png', 'img3.png'];

We can load these images in a loop:

for (let path of arr) { loadImage(path, function(image, err) { document.body.append(image); }); }

The code turned out beautiful without a callback hell, however, we returned to our two problems: an order of the images is not guaranteed and it is impossible to catch the moment of loading all the images.

And there is no solution in this situation: it is impossible to start a loop, use an async function inside it, and then catch the moment of completion of all functions of the loop. Either you don't need to catch this moment and the above code will suits you, or welcome to a callback hell.

But, you shouldn't be upset - the solution to the problem is possible via promises, which we will study in the next lessons.