'Is there a practical difference between creating Promises by hand and using the async/await API?
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?
Solution 1:[1]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
