Skip to content

Instantly share code, notes, and snippets.

@f0-x
Last active March 13, 2024 09:57
Show Gist options
  • Save f0-x/29a6aeb618c92ca337dfc0e64c190da4 to your computer and use it in GitHub Desktop.
Save f0-x/29a6aeb618c92ca337dfc0e64c190da4 to your computer and use it in GitHub Desktop.
Async TS classes using PVT methods
// Erroneous Async Class Declaration ❌
class ConfigurationLoader {
public config: any;
constructor() {
// TypeScript/Javascript Compile-time Error: Constructors cannot contain 'await'
this.config = await fetchConfiguration();
}
}
// Correct Async Class Declaration ✅
class ConfigurationLoader {
private config: any;
// This ensures that the class cannot be instantiated directly using the new keyword,
// giving the class full control over how and when instances are created.
private constructor(config: any) {
this.config = config;
}
// This method will handle the asynchronous operation and, upon completion, will
// instantiate the class using the private constructor.
public static async init(): Promise<ConfigurationLoader> {
const config = await fetchConfiguration();
// Since, the constructor is private, we can invoke
// it from inside the class definition,
// Is this some kind of recursion in declaration ? 😅
return new ConfigurationLoader(config);
}
}
async function fetchConfiguration(): Promise<any> {
// Simulate fetching configuration asynchronously
return new Promise((resolve) => {
setTimeout(() => resolve({ apiKey: "12345" }), 1000);
});
}
//👇 Instantiating the class using static method 👇
async function main() {
// This approach allows you to perform any asynchronous setup required before
// creating an instance of your class, maintaining a clean and intuitive API for class consumers.
const configLoader = await ConfigurationLoader.init();
console.log(configLoader);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment