How to handle async functions inside constructors in TypeScript

April 23, 2017

In this post we will discuss some options you have with calling async functions in constructor of your TypeScript classes.

So, first of all – why would you do this? Well, maybe you need some data from a web API to fill the object with data, or you need some input from user, or some API in code from a colleague is async. Reasons may vary, but the problem is still the same : in TypeScript, you can’t have await statement in constructor, because constructor returns instance of object, not

Promise<yourObjectType>

(All of this indeed is tied to current version of TypeScript 2.2. maybe in future with native async/await keywords in JS, things will change).

So, possible solutions depend on what happens in your async functions and if you need results from this call / calls at the time you return the object.

Solutions :

  1. Try to avoid async stuff in constructor. As said earlier, constructor is a function, that should initiate the object in some way and return it immediately, not return a promise that has to be awaited. That is considered a bad practice and TypeScript doesn’t allow this. More on this problem here

http://stackoverflow.com/questions/11856778/asynchronous-constructor

http://stackoverflow.com/questions/24398699/is-it-bad-practice-to-have-a-constructor-function-return-a-promise

http://stackoverflow.com/questions/36363278/does-async-await-will-allow-us-to-be-used-on-constructors

So in some sense, need for async stuff in your constructor might be considered code smell, you are doing too much in constructor. Refactor your code.

  1. If you want your async code to stay in constructor for some reason, do you need results from async calls? If not and you want to call them and let them just execute, you might consider calling async functions without await. In this way you will unfortunately be unable to receive (await) the result from these calls (values passed back via resolve). Please note, that this might result in some non deterministic issues because of how JS handles async code and I really don’t recommend this. Also another downside is, that if you would wrap everything inside constructor with try, promises that would be rejected (analogy with throwing exception in async sense will be not caught but become unhandled exceptions).

Your constructor might then look like this :

class SomeClass1 {
  constructor() {
    getConfirmAsync("1 – 1")
    getConfirmAsync("1 – 2")
    getConfirmAsync("1 – 3")
  }
}

Sample with try/catch block might look like this :

class SomeClass2 {
  constructor() {
    try {
      delayAsync(3000)
      delayAsync(2000)
      delayAsync(1000)
    } catch (e) {
      console.log(e)
    }
  }
}

No awaits means that code will continue to run and your constructor will finish and hand over new instance of your class sooner than code triggered from constructor will finish its execution. Scary, right? Don’t do it!!!!

Another take on this same approach is to leave an async self executing function in constructor like this :

class SomeClass3 {
  constructor() {
    console.log("SomeClass3 – entry")
    ;(async () => {
      try {
        await delayAsync(3000)
        await delayAsync(1000)
        await delayAsync(2000)
      } catch (e) {
        console.log(`catch triggered with exception ${e}`)
      }
    })()
    console.log("SomeClass3 – exit")
  }
}

Again, object would return from constructor but it would still lack calls to all async functions but this time, with proper async function, await and try/catch will work. So if for some reason first function would throw, all the others will not be hit (you can try to change the first call from 3000 to 2999 and see the results). Again, this is not recommended!

  1. Simple “factory” function :

This is a way you might potentially want to go because it’s the safest one. All calls will be awaited and instance of you class will be in the state it should be. All logic from constructor would have to be removed and stored in function that will have the logic of preparing object to the right shape. But, it is OK to separate the logic of creation from class to different function/files that knows what to do to make the object “right”? Also you might want for safety reasons to “hide” somehow the class itself to prevent from instantiation without the factory function. This could be done by exporting (from module) only interface of the object and “factory” function and not the class itself. Downside is, that all functions that are called in “factory” function need to be also public because “factory” function is not inside the class itself, but it is a separate function.

//exporting interface so we can work with the object outside
export interface ISomeClass {
        stringPublic: string;
        numberPublic: number;
    }

    //not exported = not visible
    class SomeClass implements ISomeClass {
        public stringPublic: string;
        public numberPublic: number;

    private somePrivateFn() {
            console.log("this is private fn");
        }
    }

    export async function createSomeClassAsync(): Promise<SomeClass> {
        let res = new SomeClass();

        await delayAsync(1000);
        await getConfirmAsync("1");
        await delayAsync(3000);
        await getConfirmAsync("2");
        await delayAsync(2000);
        res.numberPublic = 1;
        res.stringPublic = "aa";
        // res.somePrivateFn(); since we are not inside function this would fail

        return res;
}

This is TS that has export and import statements, but in my examples on GitHub I have this implemented without export and import. I can make a sample for you that is using modules (like the one above) but I decides to cut complexity for my readers and not use any bundling tool like webpack or browserify (I recommend webpack over browserify but that is just a matter of taste). 5. You want to hook a browser event inside the constructor, like some ready event or some other that will trigger some async functions once it happened.

Your constructor might look like this :

function ready(fn) {
  if (document.readyState !== "loading") {
    fn()
  } else {
    document.addEventListener("DOMContentLoaded", fn)
  }
}

class SomeClass {
  constructor() {
    console.log("SomeClass5 – entry")
    ready(async () => {
      try {
        await delayAsync(3000)
        await delayAsync(1000)
        await delayAsync(2000)
      } catch (e) {
        console.log(`catch triggered with exception ${e}`)
      }
    })
    console.log("SomeClass5 – exit")
  }
}

I am using a helper function from http://youmightnotneedjquery.com/ to avoid adding jQ to the project, but you get the point.

If my samples doesn’t make sense for you, please to to my GitHub repo, you can find all the code I made as examples can be found there : https://github.com/rostacik/asyncTsCtorSolutions .

If you have TypeScript installed as global npm package, just type

tsc

in the root. If you dont have TypeScript installed, you just need to do to install npm packages :

npm install

and run TypeScript compiler to build all .ts files :

"node_modules/.bin/tsc.cmd"

Hope this helps.


Profile picture

Written by Dušan Roštár - the "mr edge case" guy
my twitter : rostacik, my linkedin : rostar, drop me an email : here