4

Whenever I try to define an async function inside an object this way it throws a Syntax error.

let obj = {
  fn: async function fn() {
    return 10;
  }
}
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Seyi Adekoya
  • 443
  • 5
  • 11

1 Answers1

7

The code you posted is syntactically correct. If you are getting a syntax error then the environment you are trying to run the code in doesn't support async functions (which is not necessarily surprising giving that this feature hasn't been officially released yet).

Solutions:

  • Don't use async functions (use promises directly instead)
  • Transform your code before executing it with something like Babel.

Information about which environment supports async functions can be found at https://kangax.github.io/compat-table/es2016plus/#test-async_functions .

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143