如何停止承诺在 return 和下一个函数回调之后进一步执行?

How to stop promise to further execute after return and next function call back?

我正在 loopmodal 中检查用户 ID,然后检查电子邮件是否已经存在,但如果满足条件并退出,则必须停止进一步处理的承诺。然后我将返回下一个函数,但我的代码继续执行。以下是我的代码

User.findOne<UserPersistedModel<UserModel> & UserModel>({
      where: {email: email},
    })
    .then(user => {
    if (user) {
      error = new Error(g.f('This {{email}} is already in use.'));
      (error as HttpError).statusCode = 400;
      (error as HttpError).code = 'EMAIL_NOT_VALID';
      next(error);
      return;
    }}).then(user => console.log('Why getting here')).catch((err?: HttpError) => err && next(err));

只有两种方法可以阻止它:

  • throwthen 中跳过下一个 但是 将 运行 catch
  • Returnsomething然后用它来验证是否要运行下面的代码里面then

我认为在你的情况下,抛出你创建的错误然后让 catch 传播它看起来很有意义,例如

.then(user => {
  if (user) {
    const error = new Error(g.f('This {{email}} is already in use.'));
    (error as HttpError).statusCode = 400;
    (error as HttpError).code = 'EMAIL_NOT_VALID';
    throw error;
  }
})
.then(user => { ... }) // this part would skip
.catch(next) // you don't need to check if an error exists in `catch`, it will always exist