Consider the following snippet:
class Foo {
method = () => {
console.log('method');
}
}
const f = new Foo();
f.method();
Works just fine. But, if the function is made async instead, with no other changes:
class Foo {
method = async () => {
console.log('method');
}
}
const f = new Foo();
f.method();
This results in a syntax error. It occurs regardless of whether an arrow function is used:
class Foo {
method = function() {
console.log('method');
}
}
const f = new Foo();
f.method();
class Foo {
method = async function() {
console.log('method');
}
}
const f = new Foo();
f.method();
Is my syntax somehow incorrect, or are async functions simply prohibited in class fields?
(Of course, a plain async method on the prototype is possible too, but I'm asking why/how async functions in class fields can work)
Taking the comment's suggestion of async method() => {
doesn't work either:
class Foo {
async method() => {
console.log('method');
}
}
const f = new Foo();
f.method();