代码之家  ›  专栏  ›  技术社区  ›  Tony_Henrich

如何拒绝或停止在一系列安格拉的承诺中走得更远?

  •  0
  • Tony_Henrich  · 技术社区  · 7 年前

    我有两个函数返回对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似乎没有拒绝方法。我是不是刚从第一个承诺回来?

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

    1 回复  |  直到 7 年前
        1
  •  0
  •   Bergi    7 年前

    似乎你已经基本实现了你想要的。使 finally 等第二个电话,你 should return the inner promise then 不过是回拨。

    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 .

    推荐文章