DEV Community

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

Collapse
 
dandv profile image
Dan Dascalescu

Did you mean that more precisely, you can call super in the constructor; you can't await super() in derived class constructors, but you can extend the class if you don't need to overload the constructor? I've documented this downside in the SO answer.

Can you expand on how the constructor is not a constructor?

Thread Thread
 
yw662 profile image
yw662

A constructor should anyway return the constructed object itself, instead of a promise resolving to the said object, unless the object is the promise.

Thread Thread
 
martijn_scheffer_f5485f4b profile image
Martijn Scheffer

we are discussing creating objects asyncronously, in that case the constructor HAS to return a promise.

Thread Thread
 
somedood profile image
Basti Ortiz

Pedantically, I am on the camp that constructors should never return anything at all. That's just an unexpected quirk of JavaScript that even tsserver trips up on.

Semantically, constructors initialize fields, not return values. Thus, returning a Promise from a constructor is not only awkward, but also unexpected because it returns something aside from the intended class instance (i.e., Promise<Animal> vs. Animal itself).

A static async factory method makes this distinction well: do the async work ahead of time and then invoke the constructor with the now-resolved field initializers.