[英]javascript await function in script returns Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
I have an async function on a.js file.我在 a.js 文件上有一个异步 function 。 for example:
例如:
async function LoadProducts() {
return new Promise(resolve => {
PageMethods.set_path('/xxx/xxxx.aspx');
PageMethods.GetToken(OnSuccess, OnError);
function OnSuccess(Token) {
var settings = {
"url": "xxx",
"method": "POST",
"timeout": 0,
"headers": {
"Token": Token,
"Content-Type": "application/json; charset=UTF-8"
},
"data": JSON.stringify({
"xxx": xxx
}),
};
$.ajax(settings).done(function (response) {
$("#divProducts").append(Ret);
resolve('');
});
}
function OnError(Error) {
resolve('error');
}
});
} }
I want to call this function from html, in order to Load some products this way:我想从 html 调用这个 function,以便以这种方式加载一些产品:
<div id="divProducts">
</div>
<script>
await LoadProducts();
</script>
I get error: Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules.我收到错误:未捕获的语法错误:等待仅在异步函数和模块的顶层主体中有效。
I need to Load this part of the page before other scripts (of html template) run, that's why i use this way.我需要在其他脚本(html 模板)运行之前加载页面的这一部分,这就是我使用这种方式的原因。
Any Ideas?有任何想法吗? Thanks!
谢谢!
finally, i had to write in html this way:最后,我不得不这样写 html:
<script type="module">
await LoadProducts();
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.