我试图在多个Promise之间循环,并在if语句未经验证时退出序列,而不会引发错误(拒绝)。
看下面的代码:
return formRef.current.isValid()
.then((isValid) => {
if (isValid) {
return formatAndCreateUser(account);
}
})
.then(createResponse => {
createdUser = createResponse;
return userApi.requestToken({email: account.email, password: account.password});
})
在这里,即使isValid
变量为false,它也会通过第二个承诺。这不是我想要的...我想去formatAndCreateUser
函数是isValid
是真的,否则什么都不做...
答案 0 :(得分:3)
您应该抛出一个错误,然后处理它。如果需要,处理程序可以只是保持沉默。以下catch
将捕获then
回调中发生的错误,因此请确保在必要时进行扩展。
显然,您有一个变量createdUser
不在第二个then
回调中,因此您可以使用它来区分其他错误:
createdUser = null; // make sure to reset it (if not yet the case)
return formRef.current.isValid().then((isValid) => {
if (!isValid) throw new Error("invalid"); // throw!
return formatAndCreateUser(account);
}).then(createResponse => {
createdUser = createResponse;
return userApi.requestToken({email: account.email, password: account.password});
}).catch(err => {
if (createdUser) throw err; // just bubble the error upwards
// otherwise: do nothing (= ignore silently)
});
答案 1 :(得分:2)
如果要有条件地执行此操作,请将其移至if
块内:
return formRef.current.isValid()
.then((isValid) => {
if (isValid) {
return formatAndCreateUser(account)
.then(createResponse => {
createdUser = createResponse;
return userApi.requestToken({email: account.email, password: account.password});
});
}
});
与async
/ await
相同:
if (await formRef.current.isValid()) {
createdUser = await formatAndCreateUser(account)
await userApi.requestToken({email: account.email, password: account.password});
}
(顺便说一句,尝试避免使用全局变量createdUser
)