Ajax中失败的承诺链只有一个错误消息

时间:2017-12-18 19:52:12

标签: jquery ajax promise

如果我将我的承诺链接如下,

var promise1 = step1(), 
    promise2 = promise1.then(function(data) {
                 return step2();
               }), 
    promise3 = promise2.then(function(data) {
                 return step3();
               });

我还为每一步单独分配了失败消息。发生错误时,GUI应显示错误消息

    promise1.fail(function(data) {
        alert('A system error occurred and your action could not be completed. Please try again. Data: ' + data);
    });
    promise2.fail(function(data) {
        alert('A system error occurred and your action could not be completed. Please try again. Data: ' + data);
    });         
    promise3.fail(function(data) {
        alert('A system error occurred and your action could not be completed. Please try again. Data: ' + data);
    });     

如果Promise3中发生了某些事情,我不想传播多个错误消息。 GUI应该只显示整个链中的一个错误。这可能吗?

1 个答案:

答案 0 :(得分:1)

您不需要通过中间任务打破链条。

将其写为单个语义链

var promise = step1()
.then(function(data1) {
    return step2();
})
.then(function(data2) {
    return step3();
})
.fail(function(jqXHR, textStatus, errorThrown) {
    alert('A system error occurred and your action could not be completed. Please try again. error: ' + textStatus);
});

step1()step2()step3()中的错误将导致跳过成功路径的其余部分,并在最后渗透到失败处理程序。

这似乎是你想要的。