using await on global scope without async keyword

Update

When using Node, the file currently must have an .mjs extension to work.

Top level awaits can be used in browser modules. When used the script tag must include the type attribute which must be set to 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))
}

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

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

Leave a Comment