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

ES6中 async 和 await 是一对非常好用的搭档
利用他们能够更便捷的操作异步函数
大大提高代码可读性
但是 有一个问题
await不许在async声明的函数中使用
例如

async function getList() {
    
    
    let res = await StudentStorage.methods.queryList().call();
    console.log(res);
}

就会报错 Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
在这里插入图片描述
但是 很多时候 我们可能就是想在js代码中直接使用await 并不需要函数 例如

<script>
    let res = await StudentStorage.methods.queryList().call();
    console.log(res);
</script>

这种情况最笨的办法就是 定义一个函数再去用户async 和 await
然后调用这个函数
后面官方也对这个问题做出了处理
可以在模块中调用他
就是

<script type="module">
    let res = await StudentStorage.methods.queryList().call();
    console.log(res);
</script>

对 就是在script标签中加一个type="module"就没问题了

猜你喜欢

转载自blog.csdn.net/weixin_45966674/article/details/131669859