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
}
}