As I embark on solving this issue, I want to point out that while there are similar questions on SO based on the title, upon close examination, they seem more intricate than my specific situation. The explanations provided in those threads do not quite align with what I am experiencing.
I am seeking assistance to comprehend why the code snippet below is triggering the following error:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules.
At first glance, it appears that the problematic await
statement is indeed within a “top level” body. But could there be another definition for a top level body that I am overlooking? Any insights would be greatly appreciated!
UPDATE to differentiate from a related question mentioned here: My query does not revolve around httpGet, there are key contextual differences, and most importantly, I have received a solution that resolves my issue, unlike the answer proposed in the solitary response to the linked question. Therefore, although I found a resolution here, I believe keeping my question available could benefit the broader audience.
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();
}