Search code examples
javascriptasync-awaitecmascript-nextclass-fields

Can async functions be in class fields?


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();


Solution

  • Can async functions be in class fields?

    Yes.

    //Without BabelJS / ES2015
    class Foo {
      method = async () => {
        console.log('method');
      }
    }
    const f = new Foo();
    f.method();

    Can async functions be in class fields when using an ES2015 transpiler?

    No.

    //Without BabelJS / ES2015
    class Foo {
      method = async () => {
        console.log('method');
      }
    }
    const f = new Foo();
    f.method();

    async was introduced with ECMAScript 2017 (ECMA-262).

    In your snippets, you have Use Babel / ES2015 enabled, which predates async.