2

When I try to import a JS module dynamically using the code below, I get "Uncaught SyntaxError: unexpected reserved word" in both, Firefox and Chrome but According to MDN it should work.

let module = await import('/modules/my-module.js');

When I use .then() instead of await, everything works just fine. Is MDN wrong?

Sceptical Jule
  • 889
  • 1
  • 8
  • 26

2 Answers2

2

You should write "async" in this function declaration

 const my_func = async (arg1,arg2) => {
  let module = await import('/modules/my-module.js');
}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

Ido Levi
  • 114
  • 6
1

I was able to reproduce this error by trying to use await at the top level of a module.

Normally I would expect to see an error along the lines of "Cannot use await outside an async function" but that isn't the case here.

Moving the await import inside an async function resolved the problem:

<script type="module">
    (async function () {
        let module = await import('/modules/my-module.js');
        console.log(module);
    })();
</script>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335