v8 recently introduced top-level await
for ES modules. It’s a new proposed standard for ECMAScript, which has reached stage 3.
v8最近引入了ES模块的顶级await
。 这是ECMAScript的新提议标准,现已达到第3阶段 。
Note: it’s going to take some time before this feature will be usable in the production Node.js and in Chrome, but it’s worth taking a look
注意:要在生产中的Node.js和Chrome中使用此功能需要花费一些时间,但值得一看
Right now we can use await only inside async functions. So it’s common to declare an immediately invoked async function expression to wrap it:
现在,我们只能在异步函数中使用await。 因此,通常需要声明立即调用的异步函数表达式来包装它:
(async () => {
await fetch(/* ... */)
})()
or also declare a function and then call it:
或也声明一个函数然后调用它:
const doSomething = async () => {
await fetch(/* ... */)
}
doSomething()
Top-level await will allow us to simply run
顶级等待将使我们能够简单地运行
await fetch(/* ... */)
without all this boilerplate code.
没有所有这些样板代码。
With a caveat: this only works in ES modules. You can’t use this syntax outside of ES modules.
注意:仅在ES模块中有效 。 您不能在ES模块之外使用此语法。
Normal scripts, and CommonJS modules, will continue to use immediately invoked function expressions or creating ad-hoc function like always.
普通脚本和CommonJS模块将像往常一样继续使用立即调用的函数表达式或创建即席函数。