我应该在 Promise.all 中使用 wait 吗?

pac*_*a94 20 javascript asynchronous node.js promise express

我正在构建快速中间件,以对数据库进行两次异步调用,以检查用户名或电子邮件是否已在使用中。这些函数返回的承诺没有捕获,因为我希望将数据库逻辑与 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));
};
Run Code Online (Sandbox Code Playgroud)

然而,由于这些checkExists函数是异步的,它们不应该包含在Promise.allawait中吗?或者Promise.all自动执行此操作?

await Promise.all([
    await checkUsernameExists(username),
    await checkEmailExists(email),
  ])...
Run Code Online (Sandbox Code Playgroud)

这会导致 checkUsernameExists 拒绝未处理的承诺,并且不会向客户端发送任何响应。

Cer*_*nce 33

我应该在 Promise.all 中使用 wait 吗?

不(至少不是你这样做的方式)。Promise.all接受并期望一系列 Promises。一旦他们全部解决,或者如果其中一个人拒绝,那么他们Promise.all就会解决或拒绝。如果您使用await,您将向 传递一个普通非 Promise 值的数组Promise.all,这不是您想要的逻辑。如果您使用await,您还将等待 Promise串行解决,而不是并行解决,从而破坏 的整个要点Promise.all。例如:

await Promise.all([
    await checkUsernameExists(username),
    await checkEmailExists(email),
  ])...
Run Code Online (Sandbox Code Playgroud)

如果checkUsernameExists需要 0.5 秒来解析,并且也需要 0.5 秒来解析,那么至少checkEmailExists需要1 秒才能解析,因为 Promise 是通过s 解析的,而不是由其本身解析。Promise.allawait checkUsernameExistsPromise.all

你绝对应该这样做

await Promise.all([
  checkUsernameExists(username),
  checkEmailExists(email),
])
Run Code Online (Sandbox Code Playgroud)

异步函数返回 Promises -Promise.allsomeFnThatReturnsAPromise()相同somePromise。因此,调用该函数并将生成的 Promise 放入数组中传递给 绝对没有任何问题Promise.all