I have an array of image urls and I want to display these images on the webpage in the order of the placement of their corresponding URL in the array.
for example, we have
const imgUrls = [
"https://picsum.photos/400/400",
"https://picsum.photos/200/200",
"https://picsum.photos/300/300"
];
in which case we want to display 400/400
first, then 200/200
and lastly 300/300
.
If we implement it naively then the order is not guaranteed.
function loadImages(imgUrls, root) {
imgUrls.forEach((url) => {
const image = document.createElement("img");
image.onload = () => {
root.append(image);
};
image.src = url;
});
}
So I use Promises to manage the async flow control
async function loadImagesInOrder(imgUrls, rootEl) {
const promises = imgUrls.map(
(url) =>
new Promise((resolve, reject) => {
const image = document.createElement("img");
image.onload = resolve;
image.onerror = reject;
image.src = url;
})
);
for (const p of promises) {
const { currentTarget } = await p;
rootEl.append(currentTarget);
}
}
It works, but not all of the time. With this implementation, Sometimes some images are going to be null
so you end up with null
on the webpage.
This is the live demo https://codesandbox.io/s/load-images-in-order-t16hs?file=/src/index.js
Can someone point out what the problem is? Also is there any better way to make sure the image appear on the page in the order of the URL in the array?