Reputation: 752
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
Upvotes: 22
Views: 43188
Reputation: 37855
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
Upvotes: 22
Reputation: 15711
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
.
Upvotes: 0