How to fix SyntaxError: await is only valid in async functions and the top level bodies of modules
Variants
- SyntaxError: await is only valid in async functions, async generators and modules (Firefox)
Description
async
/ await
were great introductions to the Javascript language, replacing Promises and callbacks before that. The syntax is certainly more intuitive and generally easier to understand. Once you've learned async
/ await
, you'll want to start using it everywhere! However, there is one limitation (even in Node 18) - it cannot be used at the top level of Node. Let's look at an example:
Example
const foo = async () => {
console.log('foo');
};
await foo(); // SyntaxError: await is only valid in async functions and the top level bodies of modules
Solution
There's a little trick you can use to fix this problem - wrap all of the code in a self-executing anonymous function:
(() => {
const foo = async () => {
console.log('foo');
};
await foo();
})();
And that's it! No more issue running async
functions.