SJB
SJB

Reputation: 187

Error in global call to async function: "await is only valid in async functions and the top level bodies of modules"?

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();
}

Upvotes: 10

Views: 23728

Answers (2)

Quentin
Quentin

Reputation: 944005

Yes, it is global code - in my script.js file. And I thought what could be more "top-level" than that?

As pointed out in a comment, the problem isn't "top level" it is "in a module".

Web browsers will load scripts as modules only if the type attribute says to do so:

<script type="module" src="script.js"></script>

This enables support for import (CORS permitting), makes the script load asynchronously, and stops the top level scope being global.

Upvotes: 6

Ayzrian
Ayzrian

Reputation: 2465

The top-level await means that you are trying to use async/await syntax outside async function. The workaround is to create some function e.g. main and put the code in it.

async function main() {
  var data;
  await getData();
  document.body.write(data);
}

main();

One day top-level async/await will be supported and there is a proposal for it. Meanwhile you can use this babel plugin to use it https://babeljs.io/docs/en/babel-plugin-syntax-top-level-await without wrapper function like main.

Upvotes: 17

Related Questions