As the question stated. Will I be allowed to do this:
class MyClass { async constructor(){ return new Promise() } }
The problem arises when you're trying to call such an asynchronous method from a class constructor: you can't use the await keyword inside the constructor. As long as you're only using methods which don't return a value, you can get away with it by just calling them without await, but that's not the right way to do it.
The static async factory function pattern allows us to emulate asynchronous constructors in JavaScript. At the core of this pattern is the indirect invocation of constructor . The indirection enforces that any parameters passed into the constructor are ready and correct at the type-level.
Asynchronous learning allows you to learn on your own schedule, within a certain timeframe. You can access and complete lectures, readings, homework and other learning materials at any time during a one- or two-week period. “A big benefit to asynchronous classes is, of course, the flexibility.
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
To expand upon what Patrick Roberts said, you cannot do what you are asking, but you can do something like this instead:
class MyClass { constructor() { //static initialization } async initialize() { await WhatEverYouWant(); } static async create() { const o = new MyClass(); await o.initialize(); return o; } }
Then in your code create your object like this:
const obj = await MyClass.create();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With