Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a proper Promise with TypeScript

So I am learning Angular 2 with typescript.

I am reaching a point to write a mocking service which (I believe) should return a Promise if the service get the Object Successfully and Return an Error if anything happens.

I have tried following code but looks like it is not a write syntax for typescript.

Updated the CODE:

saveMyClass(updatedMyClass: MyClass){         //saving MyClass using http service         //return the saved MyClass or error         var savedMyClass : MyClass = someLogicThatReturnsTheSavedObject(updatedMyClass);         if(isSomeCondition)             return Promise.reject(new Error('No reason but to reject'));         else             return new Promise<MyClass>(resolve => {setTimeout( ()=>resolve(savedMyClass),1500  )}  );     } 

But to my surprise, the typescript complained that "No best common type exists among return expressions".

What should be the right code? So that I could use on my component to consume if proper MyClass is returned and reflect error if any exists from service.

Thanks

like image 256
TypingPanda Avatar asked Aug 30 '16 22:08

TypingPanda


People also ask

How do I return a promise in TypeScript?

Use the Awaited utility type to get the return type of a promise in TypeScript, e.g. type A = Awaited<Promise<string>> . The Awaited utility type is used to recursively unwrap Promises and get their return type. Copied!

How do I return the result of a promise?

There are two ways to handle promise results: . then(), which is called as a callback upon completion of the promise. async / await, which forces the current thread of execution to wait for the promise to complete.

What is promise type in TypeScript?

In TypeScript, promise type takes an inner function, which further accepts resolve and rejects as parameters. Promise accepts a callback function as parameters, and in turn, the callback function accepts two other parameters, resolve and reject. If the condition is true, then resolve is returned; else, returns reject.


1 Answers

It is considered a good practice to embed the whole function body inside the Promise constructor, so should any error happen, it would be converted to a rejection. In this case it solves your problem too I believe.

saveMyClass(updatedMyClass: MyClass) {     return new Promise<Package>((resolve, reject) => {         //saving MyClass using http service         //return the saved MyClass or error         var savedPackage : Package = updatedPackage;         if (isSomeCondition) {             throw new Error('No reason but to reject');         }          setTimeout( () => {             resolve(savedPackage);         }, 1500);     }); } 
like image 151
Tamas Hegedus Avatar answered Oct 19 '22 19:10

Tamas Hegedus