【问题标题】:How to reject or stop going further in a chain of AngularJS promises?如何拒绝或停止在 AngularJS 承诺链中走得更远?
【发布时间】:2019-06-27 14:21:33
【问题描述】:

我有两个函数可以返回对 AngularJS 的 $http.post 的调用。 这两个函数是 savePart1() & savePart2()

savePart1 = (): IPromise<any> => {
    return $http.post(....)
}

savePart2 = (): IPromise<any> => {
    return $http.post(....)
}

如果 savePart1() 失败,我试图不调用Part2()。 我做了这样的事情:

this.savePart1().then((response1) => {
    if (response1.status !== 200)
        // don't call savePart2()
        this.savePart2().then((response2) => {
            if(response1.status === 200)
            //display success message when both calls succeed
        }):
}), (error) => {
   //handle error;
}).finally();

我的问题是,如果 savePart2() 的响应未返回 200 状态(不一定是错误),如何取消调用 savePart2()。 IPromise 似乎没有拒绝方法。我只是从第一个承诺中返回吗?

我的目标是在两个调用都成功时显示成功消息。我的语法是最好的方法吗?当任何调用失败时,我想添加一个错误处理程序。

【问题讨论】:

  • "如果 savePart1() 没有返回 200 的状态,我试图不调用Part2()" - 这正是您正在做的,if 没有错陈述。还是我误解了您要查找的内容?

标签: angularjs typescript promise angular-promise


【解决方案1】:

您似乎已经实现了您想要的大部分。要让finally 等待第二次调用,您可以在then 回调中使用should return the inner promise

this.savePart1().then(response1 => {
    if (response1.status !== 200)
        return this.savePart2().then(response2 => {
//      ^^^^^^
            if (response1.status === 200)
                … // display success message when both calls succeed
            else
                … // handle non-200 status from call 2
        }, error => {
            … // handle error from call 2
        });
    else
        … // handle non-200 status from call 1
}), error => {
   … // handle error from call 1
}).finally(…);

要对错误使用通用处理程序,您可以switch from .then(…, …) to .then(…).catch(…)

this.savePart1().then(response1 => {
    if (response1.status !== 200)
        return this.savePart2().then(response2 => {
            if (response1.status === 200)
                … // display success message when both calls succeed
            else
                … // handle non-200 status from call 2
        });
    else
        … // handle non-200 status from call 1
}).catch(error => {
   … // handle errors from both calls
}).finally(…);

您甚至可以通过抛出异常来处理那里的意外状态代码:

this.savePart1().then(response1 => {
    if (response1.status !== 200)
        throw new Error("unexpected status "+response1.status);
    return this.savePart2().then(response2 => {
        if (response1.status !== 200)
            throw new Error("unexpected status "+response2.status);
        … // display success message when both calls succeed
    });
}).catch(error => {
   … // handle anything
}).finally(…);

如果您不需要两个响应值来显示成功消息,那么您甚至可以unnest the then calls

【讨论】:

    猜你喜欢
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-25
    • 2018-02-11
    • 2018-07-23
    • 2016-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多