22

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

3
  • You did import MyClass? Commented Sep 1, 2017 at 13:35
  • 2
    You could only use await inside async function. Do you wrap the code from index.js with a function? Commented Sep 1, 2017 at 13:36
  • Forgot to wrap it into an async function. Thank you all Commented Sep 1, 2017 at 14:07

2 Answers 2

22

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

Sign up to request clarification or add additional context in comments.

Comments

0

You cannot use await in the main script... Try this

async function test(){
    try {
      const result = await MyClass.getSmthg();
      return result;
    } catch(e) {}
}
test().then(function(res){console.log(res)})

await can only be used in an async function, and async function will return a promise if not called with await.

3 Comments

erm, correction: you can use await in the "main" script... But it can only be used inside an async function.
Yes, maybe my wording wasn't that good... By main script I wanted to mean the code executed directly in the global scope... AKA not in a function.
@Salketer feel free to edit your answer so that it is correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.