如何在ES模块中使用顶级等待

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模块将像往常一样继续使用立即调用的函数表达式或创建即席函数。

翻译自: https://flaviocopes.com/javascript-await-top-level/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值