I know that rejected promises should be handled with error handling.
However, I suspect that this code will not work:
public myFunction(): Promise<number>
{
try {
return this.doThingAsync(...); //Returns a promise
} catch (e) {
return Promise.resolve(7); //Fallback value
}
}
Since the first return immediately returns the promise, isn't it true that the try/catch doesn't get a chance to handle the case where the promise gets rejected? I've looked at the transpiled JavaScript and don't see anything special there, not even if I mark the function as async.
Following from that, is await required for handling of rejected promises to work in TypeScript without using the older then/catch syntax from JavaScript?
From my understanding of promises, I would expect the following to work:
public async myFunction(): Promise<number>
{
try {
const result = await this.doThingAsync(...);
return result;
} catch (e) {
return 7; //Fallback value
}
}
asyncit implicitly returns a Promise. Your function is not async, so you have to explicitly return one. You don't needawait, Justreturn Promise.resolve(7);returnand that's been around forever! TypeScript is a superset of JavaScript; that means there will always be syntax from JavaScript in TypeScript. Indeed, the only thing in the code shown here that is invalid in JavaScript (ES2020) ispublicand: Promise<number>.await, yes, but that's not a TypeScript-specific feature. I'm inclined to close as a duplicate of Difference betweenreturn await promiseandreturn promisePromise rejections in TypeScript result in exceptions and can be handled with try/catchno. No they don't. Typescript is a static type system. It compiles away. It doesn't exist at runtime so it can't "handle Promises" any differently than Javascript, in fact it doesn't handle values at runtime at all. The only reason that this has anything to do with Typescript is because the compiler is (correctly) warning you that what you think you're returning from a function isn't what you're actually returning in all cases.