patterntypescriptCritical
async constructor functions in TypeScript?
Viewed 0 times
typescriptfunctionsconstructorasync
Problem
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?
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();Solution
A constructor must return an instance of the class it 'constructs'. Therefore, it's not possible to return
You can:
-
Make your public setup
-
Do not call it from the constructor.
-
Call it whenever you want to 'finalize' object construction.
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);
}
}Code Snippets
async function run()
{
let topic;
debug("new TopicsModel");
try
{
topic = new TopicsModel();
await topic.setup();
}
catch (err)
{
debug("err", err);
}
}Context
Stack Overflow Q#35743426, score: 112
Revisions (0)
No revisions yet.