Before I begin, I acknowledge that there are several questions on SO which may sound similar to mine going by the title, however, all of them that I read are more complicated than my code and the explanation does not seem to pertain to my situation.
Can someone please help me understand what is going on in my code (snippet below) that is resulting in this error:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules.
As far as I can see, the await
which is giving rise to the error is in a "top level" body. Or is something else meant by top level body? Thanks a lot!
EDIT for differentiating from the other suggested (similar) question here: My question does not deal with httpGet, some other context is different, and most importantly I have received an answer that solves the problem for me, unlike the suggestion given in the (solitary) answer to the other question. Hence, while I have been able to find a solution here, I believe it will be valuable for the general audience for my question to stay.
var data;
await getData();
document.body.write(data);
async function getData() {
const res = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: 'GET',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-type': 'application/json'
}
});
data = await res.json();
}