DEV Community

Discussion on: The Proper Way to Write Async Constructors in JavaScript

Collapse
 
tehmoros profile image
Piotr "MoroS" Mrożek

Indeed, the async factory functions (methods if anyone prefers) seem to be the cleanest solution to the problem. Everything remains bound to the class itself. Initializing itself is still the responsibility of the class, not some outside function, we don't break the default constructor contract and avoid a ton of internal state control code inside the class. Nice. 🙂

Collapse
 
dandv profile image
Dan Dascalescu

There's an even cleaner solution.

Collapse
 
tehmoros profile image
Piotr "MoroS" Mrożek

Actually that's not cleaner. You're breaking the constructor contract, which, by definition, should return an instance of the class, not some "random" value. While ECMAScript permits this, a constructor always has a concrete role. Here, this role is broken - the constructor is not a constructor anymore: it's a async factory function which is wrapped in a class. If anything, that's more code to write than a simple function.

Thread Thread
 
somedood profile image
Basti Ortiz

Exactly my thoughts here as well! 👌