如何在JQuery&#39.deferred()中停止错误传播?

时间:2015-06-08 07:08:26

标签: javascript jquery promise

我认为fail()会阻止错误传播,但这似乎不会发生。这就是我所拥有的:

someAsynTask()
  .then(function(){
    1/0;
  })
  .fail(function(){
    console.log('Error handled.');
  })
  .then(function(){
    console.log('test'); // not printed (expected it to print)
  })
  .fail(function(){
    console.log('More errors?'); // printed (nor expecting it to print)
  });

如何让fail()捕获错误以防止它沿着promise链传播?

1 个答案:

答案 0 :(得分:1)

jQuery的两件事,最多2.x。

  • 承诺不是"抛出安全"
  • .fail()处理程序的存在不会导致下游承诺被标记为"处理"。

只有.then()有"过滤"功率,但即使使用.then(),过滤也不是自动的。

从3.0开始,我们被告知jQuery承诺将是承诺/ A +兼容。

1.x和2.x的行为是完全可预测的,甚至是可爱的,与A +不同。以下代码应该给出您期望的行为:

someAsynTask().then(function(){
    try {
        1/0;
    } catch(e) {
        return $.Deferred().reject(e).promise(); // Returning a rejected promise from a then()'s success handler is the only way to transmogrify success into failure. An uncaught `throw` does not have the same effect in jQuery 1.x and 2.x.
    }
}).then(null, function(){
    var message = 'Error handled';
    console.log(message);
    return $.when(message); //Returning a resolved promise from a then()'s fail handler is the only way to transmogrify failure into success in jQuery 1.x and 2.x.
}).then(function(msg) {
    console.log(msg); // should print 'Error handled' again
}).fail(function() {
    console.log('More errors?'); // should not print. Also, no filtering here. `.fail()` does not possess filtering power.
});