Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define an async function in an object literal

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;
  }
}
like image 425
Seyi Adekoya Avatar asked Sep 07 '25 02:09

Seyi Adekoya


1 Answers

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 .

like image 128
Felix Kling Avatar answered Sep 08 '25 15:09

Felix Kling