I have some setup I want during a constructor, but it seems that is not allowed
Which means I can't use:
How else should I do this?
Currently I have something outside like this, but this is not guaranteed to run in the order I want?
async function run() { let topic; debug("new TopicsModel"); try { topic = new TopicsModel(); } catch (err) { debug("err", err); } await topic.setup();
Async Option ConstructorThe async function call can be added right into the class instantiation step, without needing a separate init() call or having to modify your established method of class construction.
A simple answer for that: No, we can't! Currently, class constructors do not return types, and an asynchronous method should return a Task type.
Asynchronous functions are prefixed with the async keyword; await suspends the execution until an asynchronous function return promise is fulfilled and unwraps the value from the Promise returned.
A constructor must return an instance of the class it 'constructs'. Therefore, it's not possible to return Promise<...>
and await for it.
You can:
Make your public setup async
.
Do not call it from the constructor.
Call it whenever you want to 'finalize' object construction.
async function run() { let topic; debug("new TopicsModel"); try { topic = new TopicsModel(); await topic.setup(); } catch (err) { debug("err", err); } }
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