'Promise.resolve() inside async function
I read a SO thread somewhere a while back that using static Promise methods like Promise.resolve() or Promise.reject() inside an async function are anti-patterns but I can't seem to find it.
Given the following:
const asyncFunc = async (foo) => {
if (foo) return Promise.resolve()
return Promise.reject()
}
Is this considered an anti-pattern?
Solution 1:[1]
Using Promise.resolve is, perhaps not so much an antipattern so much as completely unnecessary, because returning a plain value from an async function will result in the Promise that it returns resolving to that value.
if (foo) return Promise.resolve()
is equivalent to
if (foo) return;
and
if (foo) return Promise.resolve(5)
is equivalent to
if (foo) return 5;
So you may as well leave off the Promise.resolve.
Promise.reject is a bit different. If you want to reject the Promise that the function returns, you may either do throw <expression>, or you may do return Promise.reject<expression> - both are equivalent, and I don't think there's any concrete reason to prefer one or the other in all circumstances (though I'd prefer throw since it's more concise).
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 | CertainPerformance |
