在没有async关键字的情况下在全局范围内使用await [英] using await on global scope without async keyword

查看:95
本文介绍了在没有async关键字的情况下在全局范围内使用await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在nodejs REPL中的全局范围上执行类似的操作.根据我的理解,以下两个陈述均有效. 参见文档

I am trying to do something like this on global scope in nodejs REPL. As per my understanding both the following statements are valid. see docs

let x = await Promise.resolve(2);
let y = await 2;

但是,这两个语句都抛出错误.

However, both these statements are throwing an error.

有人可以解释为什么吗? 我的节点版本是v8.9.4

Can somebody explain why? my node version is v8.9.4

推荐答案

await只能在标有async的函数中使用,因此有两种方法可以解决此问题.

await can only be used within a function that is labeled async, so there are two ways you can approach this.

注意: 有一项建议可能最终允许使用顶层等待调用

Note: There is a proposal in place that may eventually allow the usage of Top level await calls.

第一种方法是创建一个像这样的自调用函数:

The first way is to create a self invoked function like this:

(async function() {
  let x = await Promise.resolve(2)
  let y = await 2
  
  console.log(x, y)
})()

或者第二种方法是使用.then()

Or the second way is to use .then()

Promise.resolve(2).then(async data => {
  let x = data
  let y = await 2

  console.log(x, y)
})

这篇关于在没有async关键字的情况下在全局范围内使用await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆