Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
Javascript JSON fetch - skip function when response = 404

In this case I fetch review data from inside a 'for loop' as you can see here:

fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline')

As not all of the products have reviews, and thus not available which gives a 404 response back for that products. This gives me a lot of errors in the console because the specific id doesn't exist (getElementById ...).

                <script>
                fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline').then(function (response) {
                    if (response.ok) return response.json();
                }).then(function (obj) {
                    var averageScore = (obj).response.bottomline.average_score;
                    var averageTen = averageScore * 2;
                    var averageOverlay = 100 - averageScore * 20;
                    var reviewCount = (obj).response.bottomline.total_reviews;
                    var reviewCountText = "reviews";
                    console.log(obj);
                    document.getElementById("jsonproductreviewcount-{{ product.id }}").innerHTML = "<span class='reviewCount d-flex'>" + reviewCount + " " + reviewCountText + "</span>";
                    document.getElementById("sterrenOverlay-{{ product.id }}").style.width = averageOverlay + "%";
                }).catch(function (error) {
                    console.error('Oops! Errrrrorrr...');
                    console.error(error);
                })
                </script>

Should I use some IF / ELSE statement to check if the productid / response gives a 200 code? But how?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Although the people who created fetch apparently disagree, to my mind a non-success response is an error, so I always treat it as one; see ***:

fetch('https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline')
.then(function (response) {
    if (!response.ok) {                                   // ***
        throw new Error(`HTTP error ${response.status}`); // ***
    }                                                     // ***
    return response.json();
})
.then(function (obj) {
    var averageScore = (obj).response.bottomline.average_score;
    var averageTen = averageScore * 2;
    var averageOverlay = 100 - averageScore * 20;
    var reviewCount = (obj).response.bottomline.total_reviews;
    var reviewCountText = "reviews";
    console.log(obj);
    document.getElementById("jsonproductreviewcount-{{ product.id }}").innerHTML = "<span class='reviewCount d-flex'>" + reviewCount + " " + reviewCountText + "</span>";
    document.getElementById("sterrenOverlay-{{ product.id }}").style.width = averageOverlay + "%";
})
.catch(function (error) {
    console.error('Oops! Errrrrorrr...');
    console.error(error);
});

That will transfer control from your first then callback to your catch callback.


A couple of side notes:

  • There's no reason for (obj).xyz, just use obj.xyz.
  • var is effectively deprecated; new code should be written with let and/or const.
  • You might consider lighter-weight arrow functions rather than traditional functions.
  • If you can in your target environment (and it's nearly all of them now), you might consider using async/await rather than explicit promise callback functions.

For what it's worth:

fetch("https://api.yotpo.com/products/xx-apikey-xx/{{product.id}}/bottomline")
.then((response) => {
    if (!response.ok) {                                   // ***
        throw new Error(`HTTP error ${response.status}`); // ***
    }                                                     // ***
    return response.json();
})
.then((obj) => {
    const { average_score, total_reviews } = obj.response.bottomline;
    const averageTen = average_score * 2;
    const averageOverlay = 100 - average_score * 20;
    const reviewCountText = "reviews";
    console.log(obj);
    document.getElementById("jsonproductreviewcount-{{ product.id }}").innerHTML =
        `<span class="reviewCount d-flex">${total_reviews} ${reviewCountText}</span>`;
    document.getElementById("sterrenOverlay-{{ product.id }}").style.width = averageOverlay + "%";
})
.catch((error) => {
    console.error("Oops! Errrrrorrr...");
    console.error(error);
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda