我正尝试在 nodejs REPL 的全局范围 上做这样的事情。根据我的理解,以下两种说法都是有效的。 see docs
let x = await Promise.resolve(2);
let y = await 2;
但是,这两个语句都会引发错误。
谁能解释一下为什么? 我的 Node 版本是 v8.9.4
最佳答案
更新
当使用 Node 时,文件当前必须有一个 .mjs
扩展名才能工作。
顶级等待
可以在浏览器模块中使用。使用时,脚本标记必须包含 type
属性,该属性必须设置为 module
:
<script src="/script.js" type="module"></script>
const start = Date.now()
console.log('Pre call.')
await delayedCall()
console.log('Duration:', Date.now() - start)
function delayedCall() {
return new Promise(resolve => setTimeout(() => resolve(), 2000))
}
- Working Node Example -- 在终端中运行
node ./index.mjs
。 - Working Browser Example
- Supported Versions
旧答案
await
只能在标记为 async
的函数中使用,因此有两种方法可以解决这个问题。
注意: 有一项提案可能最终允许使用 Top level await。电话。
第一种方法是像这样创建一个自调用函数:
(async function() {
let x = await Promise.resolve(2)
let y = await 2
console.log(x, y)
})()
或者第二种方式是使用.then()
Promise.resolve(2).then(async data => {
let x = data
let y = await 2
console.log(x, y)
})
关于javascript - 在没有 async 关键字的情况下在全局范围内使用 await,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51525234/