承诺 – 抓住内在的一面

我有以下代码,有一些链接的承诺。 我试图在内部抛出一个错误, then我期望被外部catch ,但它不是目前的行为:

 User.getById(userId).then((user: any) => { if (user.email != email) { User.getByEmail(email).then((user: any) => { throw new OperationError("exists")); }).catch(StorageError, (err: any) => { user.email = email; return user.save(); }); } else { return user.save(); } }).then((user: any) => { return { ok: true, user: user }; }).catch(OperationError, (error: any) => { return { ok: false, message: error.message }; }).asCallback(reply); 

我怎样才能使外部捕获被throw语句的目标?

编辑按照Vohuman的build议更新代码。

 User.getById(userId).then((user: any) => { finalUser = user; if (user.email != email) { return User.getByEmail(email); } else { //I would like for this response [1] to be used in [2] return Promise.resolve(user); } }).then((user: any) => { throw new OperationError("Email already exists"); }).catch(StorageError, (error: any) => { finalUser.email = email; return finalUser.save(); }).then((user: any) => { //[2] here is where I would like the else statement to come sendEmail(user.email, subject, content); return { ok: true, user: user }; }).catch(OperationError, (error: any) => { return { ok: false, message: error.message }; }).asCallback(reply); 

现在我怎么才能在第一个else语句中parsing用户而不会被下面的陷入呢?

如果电子邮件不存在于数据库中,或者电子邮件与请求账户相同(重新发送电子邮件确认),则发送电子邮件确认。 如果电子邮件已经存在,我想中止执行。

你的做法是完全正确的,你只是忘记了一点return 。 没有它,内在的承诺就不会等待,拒绝不会触发外部的catch

 User.getById(userId).then((user: any) => { if (user.email != email) { return User.getByEmail(email).then((user: any) => { // ^^^^^^ throw new OperationError("exists")); }).catch(StorageError, (err: any) => { user.email = email; return user.save(); }); } else { return user.save(); } }).then((user: any) => { return { ok: true, user: user }; }).catch(OperationError, (error: any) => { return { ok: false, message: error.message }; }).asCallback(reply);