gpt4 book ai didi

javascript - 我应该在 Promise.all 中使用 await 吗?

转载 作者:行者123 更新时间:2023-12-05 00:25:16 29 4
gpt4 key购买 nike

我正在构建快速中间件来对数据库进行两次异步调用,以检查用户名或电子邮件是否已在使用中。函数返回没有捕获的 promise ,因为我想让数据库逻辑与 req/res/next 逻辑分开,并且我有需要 next 的集中错误处理作为论据。在我对本地环境的 postman 测试中,以下代码按预期工作,我的集中式错误处理程序将错误返回给客户端:

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 的未处理的 Promise 拒绝,并且没有响应发送回客户端。

最佳答案

Should I use await inside Promise.all?


不(至少不是你这样做的方式)。 Promise.all接受并期望一组 Promise。一旦他们都解决了,或者如果有人拒绝, Promise.all将解决或拒绝。如果您使用 await , 你将传递一个普通的非 Promise 值数组给 Promise.all ,这不是你想要的逻辑。如果您使用 await ,您还将等待 Promise 串行解决,而不是并行解决,从而击败 Promise.all 的全部要点.例如:
await Promise.all([
await checkUsernameExists(username),
await checkEmailExists(email),
])...
如果 checkUsernameExists需要 0.5 秒来解决, checkEmailExists也需要 0.5 秒才能解决, Promise.all 至少需要 1 秒解决,因为 Promise 正在通过 await checkUsernameExists 解决s,而不是 Promise.all本身。
你绝对应该这样做
await Promise.all([
checkUsernameExists(username),
checkEmailExists(email),
])
异步函数返回 Promises - 到 Promise.all , someFnThatReturnsAPromise()somePromise 相同.所以调用函数并将生成的 Promise 放入数组中传递给 Promise.all 绝对没有错。 .

关于javascript - 我应该在 Promise.all 中使用 await 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64515055/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com