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

291
Vistas
How can I wait for a promise to return in a <script> tag in raw HTML?

I have a div that fills with the view count of the page. What I want to is make a request to my server to get the view count and then render that on the page. However, since the page loads before the request responds, the text shown is [Object Promise]. The code in my <script> tag is:

<script>
    document.getElementById("viewcount").innerHTML = await fetch("https://mywebsite.com/peripherals/viewcount")
                                                     .then(function (response) {
                                                         return response.json();
                                                     }).then(function (json) {
                                                         return json.count
                                                     }).catch(function (error) {
                                                         console.log("Error: " + error);
                                                     });
</script>

How can I delay the rendering of the viewcount until a response is returned?

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

0

the text shown is [Object Promise]

This would happen if you would not use await.

When you add await, you'll get an error, because it can only be used (at the time of writing) within an async function, so wrap it:

(async function () {
    document.getElementById("viewcount").innerHTML = await fetch(/* ...etc */);
})();

You could use await all the way:

(async function () {
    try {
        const response = await fetch("https://mywebsite.com/peripherals/viewcount");
        const {count} = await response.json();
        document.getElementById("viewcount").innerHTML = count;
    } catch (error) {
        console.log("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