Home > Back-end >  Async Javascript Promise to set src of img
Async Javascript Promise to set src of img

Time:09-17

EDIT: I'm still banging my head against my desk with this.

I'm trying to set the src for a bunch of img tags in a gallery, dynamically and with javascript. Each gallery slide has img tags which I have grouped into two categories, "before" and "after". The issue is that some pages have all 8 photos, but others have less. If an image loads successfully (*In this case let's define success as the response NOT being a 404 not found), a .loaded class is added to the img which gives it a border, but if there's a 404 not found, then a .hidden class is added, which sets display: hidden to the img.

Current problem: Despite some img tags generating the following error message in the console, "GET http://blablabla/Images/gallery/job1/before-1.jpg 404 (Not Found)", the .onerror doesn't fire, the .onload does. If I inspect the img tags (which are already on the page btw) that haven't loaded, I can see they have a filled out src attribute, although ofc an image at the provided path doesn't exist. Surely it should still be an error though?

const loadImg = function (img, url) {
    return new Promise((myResolve, myReject) => {
      img.src = url;
      img.onload = myResolve(img);
      img.onerror = myReject(img);
    });
  };

  const populateBeforeImgs = function () {
    for (let i = 0; i < beforeImgs.length; i  ) {
      const img = beforeImgs[i];
      const url = `Images/gallery/job${galleryIndex}/before-${i   1}.jpg`;
      loadImg(img, url)
        .then((value) => {
          value.classList.add("loaded");
        })
        .catch((error) => {
          error.classList.add("hidden");
        });
    }
  };

  const populateAfterImgs = function () {
    for (let i = 0; i < afterImgs.length; i  ) {
      const img = afterImgs[i];
      const url = `Images/gallery/job${galleryIndex}/after-${i   1}.jpg`;
      loadImg(img, url)
        .then((value) => {
          value.classList.add("loaded");
        })
        .catch((error) => {
          error.classList.add("hidden");
        });
    }
  };

CodePudding user response:

The problem is your loadImg function:

if (Response.ok) {       

Response is defined on window, but Response.ok is undefined. Undefined evaluates to false (is a falsy value)

Try this:

const loadImg = function(img, url) {
  return new Promise((resolve, reject) => {
    img.src = url;
    img.onload = () => resolve(img);
    img.onerror = () => reject(img);
  });
};

const img1 = new Image();
const img2 = new Image();

loadImg(img1, "https://www.placecage.com/c/200/300").then((img) => console.log("image 1 loaded!")).catch(() => console.warn("img 1 failed to load"));
loadImg(img2, "https://ihopethisisnotavalidurladasdasd").then((img) => console.log("image 2 loaded!")).catch(() => console.warn("img 2 failed to load"))

  • Related