Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
Async Javascript Promise to set src of img

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");
        });
    }
  };
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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"))

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda