How to use await outside of an async function in JavaScript

avatar

Borislav Hadzhiev

Thu Dec 23 20212 min read

banner

Photo by Maik Fischer

Use await outside of an async function #

There are multiple ways to use the await operator outside of an async function:

  1. Use a Node.js version higher than 16.12.0 or set type to module in your package.json file if using Node version 14.8.0 - 16.11.0.
  2. Load the JS script as a module by setting type to module in the script tag.
  3. Use an immediately invoked function expression.

Here is the most widely supported approach - using an immediately invoked function expression.

index.js
// ๐Ÿ‘‡๏ธ Example promise const p = Promise.resolve('Hello world'); (async () => { try { const value = await p; console.log(value); // ๐Ÿ‘‰๏ธ "Hello world" } catch (err) { console.log(err); } })();

Technically, we are defining an async function here, however we call the function immediately and get access to the resolved value.

If the promise is rejected, the reason for its rejection will get passed to the catch block.

If you're working on the client side, you can check the browser support for the top level await feature in this caniuse table.

At the time of writing, we are able to use the top level await feature by setting the type attribute to module when loading the JS file.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โœ… type is set to module โœ… --> <script type="module" src="index.js"></script> </body> </html>

This enables us to use top level await directly.

index.js
const p = Promise.resolve('Hello world'); try { const value = await p; console.log(value); // ๐Ÿ‘‰๏ธ "Hello world" } catch (err) { console.log(err); }
When using top level await, it's very important to use a try/catch block, because an uncaught exception caused by a rejected promise might crash your application.
index.js
// ๐Ÿ‘‡๏ธ Example rejected promise const p = Promise.reject('Something went wrong'); try { const value = await p; console.log(value); } catch (err) { // ๐Ÿ‘‡๏ธ catch the error here console.log(err); // ๐Ÿ‘‰๏ธ "Something went wrong" }
If you are on the server side and using Node.js version greater than 16.12.0, you can directly use top level await without changing anything.

If your Node.js version in in the range 14.8.0 - 16.11.0, you need to set the type property to module in your package.json file.

package.json
{ "type": "module", // ...rest }

If your project does not have a package.json file, you can create one by issuing the npm init -y command.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee