【问题标题】:Only One Error Message from a Failed Promise Chain in AjaxAjax 中失败的 Promise 链只有一个错误消息
【发布时间】:2017-12-20 09:34:36
【问题描述】:

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

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 应该只显示整个链中的一个错误。这可能吗?

【问题讨论】:

  • 呃,不是每个承诺都有单独的失败消息吗? promise3 无论如何都会被拒绝,如果你的链中的任何地方出现错误,那么就使用它。

标签: jquery ajax promise


【解决方案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() 中的错误将导致成功路径的其余部分被跳过,并最终渗透到失败处理程序。

这似乎是你想要的。

【讨论】:

    猜你喜欢
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-30
    相关资源
    最近更新 更多