0

I have an async function on a .js file. 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 :

<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.

Any Ideas? Thanks!

aynber
  • 22,380
  • 8
  • 50
  • 63
  • There's no reason to mark the function as `async` if you're not using `await` inside of it. – Bergi Sep 09 '22 at 18:10
  • Using async with `new Promise` is also an anti-pattern https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it – evolutionxbox Sep 09 '22 at 18:11

1 Answers1

0

finally, i had to write in html this way :

<script type="module">
    await LoadProducts();
</script>