我正在以循环方式检查用户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));
答案 0 :(得分:0)
只有两种方法可以阻止这种情况:
throw
内的then
会跳过下一个,但会运行catch
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