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.
Top comments (3)
Nice one! :D
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.
"or renaming your .js file to .mjs"
files with an S. There's no mixing of files that have require() anywhere in them. When I fist read the above I was hoping I wouldn't have to refactor so much files. Renaming files to .mjs serves no purpose that I see. You are going to have to refactor all the require statements in the code no matter what. The additional labor of renaming files feels pointless.