Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
407 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...