顶级等待在 ECMAScript 中不起作用

0 javascript async-await es6-modules top-level-await

我很困惑,因为我读到 ESM 支持顶级等待,但是当我在 html 文件中尝试它时它不起作用?

我是否发现这样说: 顶级等待不适用于节点 14.13.- “顶级等待仅适用于 ESM 模块”

ESM 是否支持顶级等待以及如何使用它。

document.getElementById('foo').innerHTML = 'hello1';
await pause(2000); // is this possible if so how
document.getElementById('foo').innerHTML = 'hello2';
Run Code Online (Sandbox Code Playgroud)

Cer*_*nce 5

是的,ESM - ES6 模块支持它。纯脚本标签支持它。

<script>
await Promise.resolve();
</script>
Run Code Online (Sandbox Code Playgroud)

您需要指定该脚本是一个模块才能运行。

<script type="module">
await Promise.resolve();
console.log('finished successfully');
</script>
Run Code Online (Sandbox Code Playgroud)

(还要确保您在受支持的环境中运行它 - 较旧的环境可能不支持顶级等待)