为什么承诺会以未回报的价值转到其他承诺

时间:2019-12-24 14:54:22

标签: javascript

我试图在多个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是真的,否则什么都不做...

2 个答案:

答案 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

相关问题