I'm building express middleware to make two async calls to the database to check if the username or email are already in use. The functions return promises without a catch, as I want to keep database logic seperate from req/res/next logic, and I have centralised error handling that requires next as an argument. In my postman testing on local environment the following code works as expected and my centralised errorhandler returns the error 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, as the checkExists functions are async, shouldn't they be included in Promise.all with await? Or does Promise.all do this automatically?
await Promise.all([
await checkUsernameExists(username),
await checkEmailExists(email),
])...
This leads to an unhandled promise rejection from checkUsernameExists and no response is sent back to the client.