Search code examples
javascriptasync-awaites6-promisefetch-api

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


Solution

  • 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.