CertainPerformance highlighted in my previous post advised me to avoid the explicit Promise construction antipattern with reference to to following question
It never makes sense to create a promise with promise constructor when there's existing promise, that's why it's called promise construction antipattern.
This is a mistake, reject("Error in findUserByEmail", error)
. reject
accepts only 1
argument, which is rejection reason. error
will be ignored. It's conventionanl for an error to be Error
object and not a string.
The function may be refactored to:
const findUserByEmail = (emailAddress) => {
return User.findOne({email: emailAddress})
.then(response => response) // noop
.catch(error => {
const readableError = new Error('Error in findUserByEmail');
readableError.originalError = error;
throw readableError;
});
})
}
etc.
Antipatterns don't necessary result in bad performance but they result in code smell. They make the code harder to read, maintain and test, also show that a developer may have a poor understanding of the subject.
Promise constructor has some insignificant performance impact. It introduces another level of nesting and contributes to callback hell - promises are supposed to help avoiding it.
If I change my above code snippet without adding new promise <...> Then I won't probably be able to .then and .catch in findUserByEmail("test@example.com")?
No, a promise can be chained with then(...)
and catch(...)
(which is syntactic sugar for then(null, ...)
) as many times as needed, that's the strong side of the pattern. Notice that catch(err => { return err })
and catch(err => { throw err })
is not the same thing, the former catches an error, the latter rethrows it.