using await on global scope without async keyword

前端 未结 5 562
猫巷女王i
猫巷女王i 2020-12-11 02:46

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



        
相关标签:
5条回答
  • 2020-12-11 03:25

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

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

    0 讨论(0)
  • 2020-12-11 03:28

    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

    0 讨论(0)
  • 2020-12-11 03:29

    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.

    0 讨论(0)
  • 2020-12-11 03:33

    You could wrap all the code in the global scope in an async function.

    For example:

    // ...global imports...
    
    new Promise (async () => {
    
      // ...all code in the global scope...
    
    }).then()
    
    0 讨论(0)
  • 2020-12-11 03:47

    This proposal is currently in stage 3 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

    0 讨论(0)
提交回复
热议问题