我试图在多个 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,它也会执行第二个 Promise。这不是我想要的...我想使用 formatAndCreateUser
函数,如果 isValid
为 true,则不执行任何操作...
最佳答案
您应该抛出一个错误,然后处理它。如果您愿意,处理程序可以保持沉默。以下 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)
});
关于javascript - 为什么 promise 会在未返回值上转到其他 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59470474/