Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SyntaxError when calling an async static function

I'm playing a bit with async/await of Node 8.3.0 and I have some issue with static function.

MyClass.js

class MyClass {
  static async getSmthg() {
    return true;
  }
}
module.exports = MyClass

index.js

try {
  const result = await MyClass.getSmthg();
} catch(e) {}

With this code I've got an SyntaxError: Unexpected token on MyClass. Why is that? Can't use a static function with await or have I made a mistake?

Thank you

like image 385
NorTicUs Avatar asked Sep 01 '17 13:09

NorTicUs


1 Answers

The await operator can only be used inside a async function if your node or browser don't support top level await and it doesn't run as a module.

You would have to do this instead

(async () => {
  try {
    const result = await MyClass.getSmthg();
  } catch(e) {}
})()

the alternative can be to set "type": "module" in package.json

like image 177
Endless Avatar answered Oct 11 '22 14:10

Endless