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?
CodePudding user response:
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);
}
})();