【发布时间】:2021-02-07 09:46:28
【问题描述】:
我正在构建快速中间件以对数据库进行两次异步调用,以检查用户名或电子邮件是否已在使用中。这些函数在没有捕获的情况下返回承诺,因为我想让数据库逻辑与 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 中并带有await 吗?还是Promise.all 会自动执行此操作?
await Promise.all([
await checkUsernameExists(username),
await checkEmailExists(email),
])...
这会导致来自 checkUsernameExists 的未处理的 Promise 拒绝,并且没有响应发送回客户端。
【问题讨论】:
标签: javascript node.js express asynchronous promise