Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

282
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!