在写JavaScript时代码中使用了await关键字然后报错是如下:
Error in global call to async function: "await is only valid in async functions and the top level bodies of modules"?
我们是知道的在JavaScript的新版中引入了异步的概念,即使我在function 中使用 await还是同样会报错如下:
async function getData(){
await ......
}
这种用法是不被支持的,如果你想要使用javascript的异步首先你得了解它的模块概念,即module 。它是一种JavaScript 程序拆分为可按需导入的单独模块的机制,此时才有异步概念。要使用 async 和 await 请在模块中使用。就是说你应该把代码放到模块中(文件)中,然后引入进来,像下面这样:
<script type="module" src="script.js"></script>