Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

async constructor functions in TypeScript?

I have some setup I want during a constructor, but it seems that is not allowed

no async const

Which means I can't use:

await

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(); 
like image 275
dcsan Avatar asked Mar 02 '16 09:03

dcsan


People also ask

Can constructors be async TypeScript?

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.

Can we use async in constructor?

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.

What does async function do in TypeScript?

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.


1 Answers

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:

  1. Make your public setup async.

  2. Do not call it from the constructor.

  3. 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);     } } 
like image 86
Amid Avatar answered Sep 17 '22 17:09

Amid