im trying to load multiple images using an async function and a regular for function, and for some reason only the last image of the called is being loaded onto the dom.. I think it has to do with the global variable however I cant quite get a grip on why.
let imgEl; const imageContainer = document.querySelector('.images'); function createImage(imgPath) { return new Promise((resolve, reject) => { imgEl = document.createElement('img'); imgEl.src = imgPath; imgEl.addEventListener('load', () => { document.querySelector('.images').append(imgEl); resolve(imgEl); }); imgEl.addEventListener('error', e => reject(e)); }); } async function loadAll(...imgPaths) { try { const res = await Promise.all( imgPaths.map(async imgPath => await createImage(imgPath)) ); res.forEach(el => el.classList.add('paralell')); } catch (error) { console.log(error); } } loadAll('/img/img-1.jpg', '/img/img-2.jpg', '/img/img-3.jpg');
By the time the load
event on any of the images has fired, the value of imgEl
been overwritten by the last call to imgEl = document.createElement('img');
.
This means the last image gets appended multiple times (initially adding it to the DOM and then moving it from where it is to … well … the same place several times).
The earlier images get garbage collected as there are no references left to them.
Define imgEl
inside the function you pass to new Promise
; don't make it a global. It doesn't need to be shared between multiple functions or multiple invocations of the same function.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.