using await on global scope without async keyword

℡╲_俬逩灬. 提交于 2019-12-07 04:20:33

问题


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.

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


回答1:


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

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)
})()

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)
})



回答2:


You can not do that. MDN doc says

The await operator is used to wait for a Promise. It can only be used inside an async function.




回答3:


This proposal is currently in stage 2 of the TC39 process. LINK

You can use this feature in Google Chrome and Mozilla Firefox as of now. You can use top level await without async in console.

https://twitter.com/addyosmani/status/1080365576218759168




回答4:


since node 10, you can run node process with --experimental-repl-await to allow to level await https://nodejs.org/api/repl.html#repl_await_keyword



来源:https://stackoverflow.com/questions/51525234/using-await-on-global-scope-without-async-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!