using await on global scope without async keyword
As of version 13.3, Node.js support Top-level await.
Top-level await
means you can now use await
operator outside an async
function. So both examples are correct:
(async function() {
await Promise.resolve(console.log('Hello await!'));
}());
// or
await Promise.resolve(console.log('Hello await!'));
Note: Top-level await only works at the top level of modules. There is no support for classic scripts or non-async functions.
Just keep in mind, that the await
operator is used to wait for a Promise. It does NOT matter if you are using an await
operator with a value other than a Promise. For example, the name
variable in the displayName()` function:
async function displayName() {
const name = await 'unclexo';
console.log(name);
}
displayName(); // outputs 'unclexo'
As the value of the name
variable is not a Promise, it converts the value to a resolved Promise, and waits for it. It happens under the hood.
The old behavior
MDN doc says
The await operator is used to wait for a Promise. It can only be used inside an async function.
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))
}
- Working Node Example -- Run
node ./index.mjs
in the terminal. - Working Browser Example
- Supported Versions
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)
})
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