10

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

17
  • 6
    of modules — This probably isn't a module, but simply global code? Commented May 25, 2021 at 13:06
  • 1
    It certainly isn't a module in a stack snippet. Commented May 25, 2021 at 13:08
  • 1
    is it necessary to wrap the fetch call inside getData() method? Commented May 25, 2021 at 13:08
  • 1
    Does this answer your question? How to resolve the Syntax error : await is only valid in async function? Commented May 25, 2021 at 13:11
  • 1
    It doesn't, hence it being a comment and not part of my answer. Commented May 25, 2021 at 13:43

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. So I just need to put a wrapper around it, that's all? What's the point/difference syntactically/logically speaking?
I mean the point is, that if I put a wrapper around it, then I will need to call it from another function - and I DO NOT want to call it asynchronously. I want the fetch call to complete and all of the data to be loaded before the execution moves on. Is there a way I can achieve that?
Well, putting await is just syntax sugar for Promises. It will wait for the promise to resolve and then will execute the code below, but because HTTP requests are async some other code also may be executed. So it should does what you need in your case, it will wait the getData execution and then document.body.write call will be executed.
That's precisely the issue. If I don't put await then "some other code" gets executed before the data download completes and that causes unwanted behavior.
You can call the wrapper in the script and the wrapper will contain all the code that you have to execute, and because you put await the code will wait for async requests before doing other stuff. You can make HTTP requests sync if you want to remove async behaviour.
|
6

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.

1 Comment

Thanks! I tried adding the type="module" attribute and as of now it seems to have worked! The script stops and waits for the function call to complete, and then proceeds further. So there is a solution! I appreciate the other responses as well but apparently it can be done, unlike what they say.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.