Top level await
works correctly when I run it in live server plugin (or edit live Webstorm IDE); however, that code throws an error when I deploy it with npx parcel index.html
.
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
const res = await Promise.resolve('hi there');
console.log(res)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<script type="module" defer src="script.js"></script>
<title>parcel and top-level-await</title>
</head>
<body>
</body>
</html>
{
"devDependencies": {
"parcel": "^2.2.1"
},
"name": "top-level-await",
"version": "1.0.0",
"main": "index.js",
"author": "elmi-elmi",
"license": "MIT"
}
await
can only be used in modules, so it doesn't work. You have to tell Parcel to output a module file instead. There seems to be anoutputFormat
option for controlling it, but I don't use Parcel and didn't get it working in the few minutes of fiddling I did. There's also this open issue about TLA. – Peonir