![](/img/trans.png)
[英]SyntaxError: await is only valid in async functions and the top level bodies of modules
[英]javascript await function in script returns Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
我在 a.js 文件上有一個異步 function 。 例如:
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');
}
});
}
我想從 html 調用這個 function,以便以這種方式加載一些產品:
<div id="divProducts">
</div>
<script>
await LoadProducts();
</script>
我收到錯誤:未捕獲的語法錯誤:等待僅在異步函數和模塊的頂層主體中有效。
我需要在其他腳本(html 模板)運行之前加載頁面的這一部分,這就是我使用這種方式的原因。
有任何想法嗎? 謝謝!
最后,我不得不這樣寫 html:
<script type="module">
await LoadProducts();
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.