let newArr = [];
let paths = ['1.jpg', '2.jpg', '3.jpg'];
function promiseAllImg(arr) {
for (let i = 0; i < arr.length; i++) {
let image = document.createElement('img');
image.src = arr[i];
return new Promise(function(resolve, reject) {
image.addEventListener('load', function() {
resolve(image);
})
image.addEventListener('error', function() {
reject('error');
})
})
}
}
newArr.push(promiseAllImg(paths));
Promise.all(newArr).then(function(res) {
for (let i = 0; i< newArr.length; i++) {
document.body.appendChild(res[i])
}
})
I need to show all images, but this programm shows only the first image. What is the problem in my programm? Write a code that will wait until all the images are loaded, and then add them in a loop to the end of the body.
You are returning inside a
for
loop.During the first iteration of the loop, the code hits
return
and returns which ends the function.You should replace the
for
loop with themap
method of your array.That will run a function for each item in an array and then return an array containing all the results (i.e. the promises).