Top Level Await in Node

mikeesto

Michael Esteban

Posted on August 15, 2020

Top Level Await in Node

Node v14.8.0 was released this week and with it came the unlocking of a commonly requested feature that I am excited about!

You may have run into the dreaded await is only valid in async function syntax error when trying to write code like this:

const res = await fetch("https://dev.to");

// SyntaxError: await is only valid in async function
Enter fullscreen mode Exit fullscreen mode

As a workaround, it was common to see codebases use an immediately invoked function expression:

(async function() {
  const res = await fetch("https://dev.to");
}());
Enter fullscreen mode Exit fullscreen mode

Ugly - but functional! Alternative options include transpiling with Babel or using the command line flag --harmony-top-level-await.

With v14.8.0, top level await has been unflagged and now just works. The only catch is that top level await is only supported in ES modules. This means either adding "type": "module" to your package.json file or renaming your .js file to .mjs.

If your project can work with v14.8.0, you can take advantage of this feature today. For everyone else, you will still need to await a while.

💖 💪 🙅 🚩
mikeesto
Michael Esteban

Posted on August 15, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related