# How to use top-level await in JavaScript

> Learn how top-level await lets you use await outside an async function, dropping the IIFE boilerplate, and why it only works inside ES modules and .mjs files.

Author: [Flavio Copes](https://flaviocopes.com/about/) | Published: 2019-11-05 | Updated: 2021-06-26 | Topics: [JavaScript](https://flaviocopes.com/tags/js/) | Canonical: https://flaviocopes.com/javascript-await-top-level/

Usually can use await _only inside async functions_. So it's common to declare an immediately invoked async function expression to wrap it:

```js
(async () => {
  await fetch(/* ... */)
})()
```

or also declare a function and then call it:

```js
const doSomething = async () => {
  await fetch(/* ... */)
}

doSomething()
```

Top-level await will allow us to simply run

```js
await fetch(/* ... */)
```

without all this boilerplate code.

With a caveat: this only works in [ES modules](https://flaviocopes.com/how-to-enable-es-modules-nodejs/). 

For a single [JavaScript](https://flaviocopes.com/javascript/) file, without a bundler, you can save it with the `.mjs` extension and you can use top-level await.
