Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic separate from the request/response/next logic. Additionally, I have centralized error handling that requires 'next' as an argument. During testing with Postman in my local environment, the code below behaves as expected and the centralized error handler effectively returns any errors to the client:
async checkUsernameExists(username) {
await this.sequelize.transaction(
async () =>
await this.User.findOne({
where: {
username,
},
}).then(user => {
if (user) throw new Conflict('Failed. Username already in use.');
}),
);
}
const checkDuplicateUsernameOrEmail = async (
{ body: { email, username } },
res,
next,
) => {
await Promise.all([
checkUsernameExists(username),
checkEmailExists(email),
])
.then(() => next())
.catch(error => next(error));
};
However, since the 'checkExists' functions are asynchronous, should they not be included in 'Promise.all' with the 'await' keyword? Or does 'Promise.all' handle this behavior automatically?
await Promise.all([
await checkUsernameExists(username),
await checkEmailExists(email),
])...
This results in an unhandled promise rejection from 'checkUsernameExists' and no response being sent back to the client.