TypeScript Learner
TypeScript Learner

Reputation: 195

How to wait for other functions answers in typescript?

I am pretty new to typeScript, I am trying to make a simple JavaScript library using TypeScript.

I have an event listener which is for window load and when the window loaded I fill some of my config (which are variables) and I need to run other functions after the load callback and also those configs filler.

I used a library which is for promise but that was very heavy and also not famous on GitHub, when I added to the typeScript the bundled javascript file became over 15k! I just wrote some lines of code but the promise was complicated!

What should I do for promises?

Upvotes: 1

Views: 152

Answers (1)

Bruno Grieder
Bruno Grieder

Reputation: 29824

Use typescript >= 2.1 (if you need to compile to ES5), >= 1.7 (for ES6 only) and async/await

try {

    const result = await funcThatReturnsAPromise()
    //do other stuff after the promise succeeded

} catch(e) {

   //do stuff when promise fails (rejects)
}

Documentation for 1.7

Support for ES3/ES5 target in 2.1

Support for ES3/ES5 TL;DR;

  • add a Promise Polyfill
  • change compiler options in tsconfig.json

     "compilerOptions": {
         "lib": ["dom", "es2015.promise", "es5"]
     }
    

Upvotes: 2

Related Questions