loading...

Top Level Await in Node

mikeesto profile image Michael Esteban ・1 min read

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

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

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

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.

Discussion

pic
Editor guide
 

Yes, this is a major advance. :)

It means that a module can load resources dynamically.

On the other hand, it also means that loading a module can be an indefinitely blocking operation, so ymmv, and you may need to consider defensive asynchronous imports.

 

For everyone else, you will still need to await a while.

Nice one! :D