我正在构建快速中间件,以对数据库进行两次异步调用,以检查用户名或电子邮件是否已在使用中。这些函数返回的承诺没有捕获,因为我想将数据库逻辑与 req/res/next 逻辑分开,并且我有集中的错误处理,需要next
作为一个论点。在我对本地环境的邮递员测试中,以下代码按预期工作,并且我的集中式错误处理程序将错误返回给客户端:
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));
};
然而,作为checkExists
函数是异步的,不应该包含在Promise.all
与等待?或者确实Promise.all
自动执行此操作吗?
await Promise.all([
await checkUsernameExists(username),
await checkEmailExists(email),
])...
这会导致 checkUsernameExists 拒绝未处理的承诺,并且不会向客户端发送任何响应。