全局调用异步函数出错:"await is only valid in async functions and the top level bodies of modules"?

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

在我开始之前,我承认有几个关于 SO 的问题听起来 与我的标题相似,但是,我阅读的所有问题都是 比我的代码更复杂,解释似乎不适合我的情况。

谁能帮我理解导致此错误的代码(下面的代码段)中发生的事情:

Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules.

据我所知,导致错误 await 是“顶级”body 中的 。还是顶级 body 有其他含义?非常感谢!

EDIT 用于区分其他建议的(类似)问题 我的问题不涉及 httpGet,其他一些上下文不同,最重要的是,我收到了一个为我解决问题的答案,这与对另一个问题的(单独)答案中给出的建议不同。因此,虽然我已经能够在这里找到解决方案,但我相信对于普通观众来说,留下我的问题将是有价值的。

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

顶级 await 意味着您正试图在 async 函数之外使用 async/await 语法。解决方法是创建一些功能,例如main 并将代码放入其中。

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

main();

一天顶层async/await将得到支持,并且有一个提案。同时你可以使用这个 babel 插件来使用它 https://babeljs.io/docs/en/babel-plugin-syntax-top-level-await 而没有像 main.

这样的包装函数

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

正如评论中指出的那样,问题不是“顶级”问题,而是“在模块中”。

仅当 type 属性要求这样做时,Web 浏览器才会将脚本作为模块加载:

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

这会启用对 import 的支持(允许 CORS),使脚本异步加载,并停止全局作用域。