Reputation: 30528
I've inherited a codebase which is full of functions like this:
const someFunc = async (): Promise<string> => {
return new Promise(async (resolve, reject) => {
try {
const result = await doSomething();
resolve(result);
} catch (error) {
reject(error);
}
});
};
It is my understanding that since the error is not handled in the catch
this is essentially the same as doing this:
const someFunc = (): Promise<string> => {
return doSomething();
};
Did I miss something?
Upvotes: 2
Views: 54
Reputation: 664297
This is horrible indeed. Never pass an async function
as the executor to new Promise
!
Did I miss something?
Synchronous exceptions thrown by doSomething
. We assume it returns a promise, so this should never happen, but if they do, then your code is not strictly equivalent to the original which returns a rejected promise. You'd fix this by simply making it an async
function:
// eslint-disable-next-line require-await -- async is used to catch the synchronous exceptions
const someFunc = async (): Promise<string> => {
// ^^^^^
return doSomething();
};
If this is not an issue, you could shorten the code even further:
const someFunc: () => Promise<string> = doSomething;
Upvotes: 2