DEV Community

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

Collapse
 
itays123 profile image
Itay Schechner

Great article. Coming from a Java perspective, it might be best to call your async factories getInstance(...) instead of initialize or fetchUser

Collapse
 
somedood profile image
Basti Ortiz

That is true, but the getInstance naming convention implies the singleton pattern, which is not the case here. The factory function here constructs a whole new instance (rather than returning a singleton).

Collapse
 
itays123 profile image
Itay Schechner

That's true, but regardless of the singleton pattern, I still find it more readable

Thread Thread
 
somedood profile image
Basti Ortiz

Ah, I see. I did point out that this was the unfortunate downside to this pattern: the lack of a standardized interface for object construction. Before, all we had to use was the new keyword. With factory functions, we have to adhere to the naming conventions of the project, which may not be the standard everywhere.

Thread Thread
 
darlanalves profile image
Darlan Alves

Cool trick indeed!

You could define one factory by convention, e.g. await Spotify.create(code) and apply in your codebase.

I'd prefer that to "fetchUser", because you will need more static methods if you want to add behavior.

A single entry point for a class, and then you can have as mathods as necessary.

Thread Thread
 
somedood profile image
Basti Ortiz

I totally agree! This is actually how it's done in the Rust ecosystem. Though, instead of create, the typical naming convention is new. But create also conveys the same semantics! 👌