javascript - 为什么 promise 会在未返回值上转到其他 promise

标签 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,它也会执行第二个 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/

相关文章:

javascript - 定位嵌入在 JavaScript 中的元素

javascript - 如何从多个文件导入图标以 react native 矢量图标?

javascript - IE 中的 Z 索引 : li element disappeared when over on it

javascript - 模拟两个圆圈相互弹跳

javascript - 查找问号前的单行文本的正则表达式是什么?

javascript - Angularjs:对象数组中的 ng-repeat 过滤器对象

javascript - 按一次迭代后停止的日期值对 JSON 数组进行排序

javascript - 在自定义 AJAX 请求上显示 Turbolinks 加载栏

javascript - 如何通过网页控制游戏服务器?

javascript - 隐藏 Chart.js 中的所有标签和工具提示并使其非常小